`

synchronized(this) vs synchronized(Class)

 
阅读更多
package com.yan.threads;

public class TestThread {

	public static void main(String[] args) {
		//同一对象:this,class //不能并发
		/*MyThread myThread = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread);*/
		
		//同一对象:class,class  //同一锁竞争,不能并发
		/*MyThread myThread = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread);*/
		
		//同一对象:this,this //同一锁竞争,不能并发
		MyThread myThread = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread);
		
		//不同对象:this,this //可以并发
		/*MyThread myThread = new MyThread();
		MyThread myThread2 = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread2);*/
		
		//不同对象:class,this //可以并发
		/*MyThread myThread = new MyThread();
		MyThread myThread2 = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread2);*/
		
		//不同对象:class,class  //不能并发
		/*MyThread myThread = new MyThread();
		MyThread myThread2 = new MyThread();
		Thread t1 = new Thread(myThread, "t1");
		t1.start();
		processThread(myThread2);*/
	
	}
	
	public static void processThread(MyThread thread) {
		thread.run2();
		
	}
}


class MyThread implements Runnable {

	@Override
	public void run() {
		synchronized(MyThread.class) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for(int i=0;i<50;i++)
				System.out.println("Thread "+Thread.currentThread().getName()+" "+i+" is running");
			
		}
		
	}
	
	public void run2() {
		synchronized(MyThread.class) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for(int i=0;i<50;i++)
				System.out.println("Thread "+Thread.currentThread().getName()+" "+i+" is running in run2");
			
		}
		
	}
	
}


分享到:
评论

相关推荐

    java中synchronized用法

    在 Java 中,synchronized 关键字可以作用于 instance 变量、object reference(对象引用)、static 函数和 class literals(类名称字面常量)身上。 Synchronized 关键字的作用是取得对象的锁,而不是把一段代码或...

    深析Synchronized关键字(小白慎入,深入jvm源码,两万字长文)

    目录一、synchronized基础1.1synchronized的使用1.1示例1.2验证1.2.1 普通方法和代码块中使用this是同一个监视器(锁),即某个具体调用该代码的对象1.2.2 静态方法和代码块中使用该类的class对象是同一个监视器,...

    PHP pthreads v3下同步处理synchronized用法示例

    本文实例讲述了PHP pthreads v3下同步处理synchronized用法。分享给大家供大家参考,具体如下: ...class Count extends Thread { public $cnt = 0; public function run() { $this-&gt;add(); } public funct

    SynchorizedDemo

    synchronized(this)与synchronized(class) 简单实例 分类: Android Java

    oa源码 大型oa asp.net 源码

    public partial class login2 : Page { [AccessedThroughProperty("chpwd")] private ImageButton _chpwd; [AccessedThroughProperty("dropBranch")] private DropDownList _dropBranch; ...

    java聊天室源程序

    public class BroadCast extends Thread { ClientThread clientthread; ServerThread serverthread; String str; public BroadCast(ServerThread serverthread) { this.serverthread = serverthread; } ...

    Java学习题答案

    (15分) 主要相同点: Lock能完成synchronized所实现的所有功能.(其它不重要) 主要不同点: Lock有比synchronized更精确的线程语义和更好的性能(在相同点中回答此点也行) synchronized会自动释放锁....

    android的 AIDL 例子

    public class IPersonImpl extends IPerson.Stub{ // ������������ private int age; private String name; @Override // ��ʾname��age public String display() throws RemoteException { ...

    Java自定义异常案例--ExceptionManager(java源码)

    * This class &lt;code&gt;ExceptionManager&lt;/code&gt; and its subclasses are a form of * &lt;code&gt;Exception&lt;/code&gt;. It is used to wrap all the &lt;code&gt;Throwable&lt;/code&gt; instances * and handle them in a unified way...

    java课程设计

    synchronized (this){ if(isplay) chosenClip.play(); else { try{this.wait();} catch(InterruptedException e){e.printStackTrace();} }//else try { this.wait(); } catch (InterruptedException e) ...

    j2me手机蓝牙OBEX传文件代码

    synchronized(this){ this.notify(); } } public void servicesDiscovered( int transID, ServiceRecord[] servRecord ) {} public void serviceSearchCompleted( int transID, int respCode ) {} } 7.服务查询...

    SVGPathView

    /** * PathView is an View that animate ... * or resided it must be synchronized with this object. */ private final Object mSvgLock = new Object(); /** * Thread for working with the object above.

    用Java语言开发的网络蚂蚁,很实用哦

    public class DownLoad{ URL url; String objFile; long nStartPos; RandomAccessFile rf; public DownLoad(String objFile,long nStartPos) throws IOException{ this.nStartPos=nStartPos; this.objFile=...

    缓存穿透.txt

    synchronized (this){ allUserCount= (Long) redisTemplate.opsForValue().get(Constants.ALL_USER_COUNT); if(allUserCount==null){ allUserCount=userMapper.selectAllUserCount(); redisTemplate....

    JAVA实现SOCKET聊天

    public class ChatHandler implements Runnable { protected Socket socket; protected ObjectInputStream dataIn; protected ObjectOutputStream dataOut; protected Thread listener; protected static ...

    Java 2实用教程(第三版)实验指导与习题解答

    public class MainClass { public static void main (String args[ ]) { System.out.println("你好,只需编译我") ; //命令行窗口输出"你好,只需编译我" A a=new A(); a.fA(); B b=new B(); b.fB(); } } ...

    [工具软件] Netkit Package for .NET 5.0.6132

    A set of .NET classes that makes the work of querying DNS servers for resource record types defined by RFC-1034 and RFC-1035, and performing domain registration with the WhoIs class more easily....

    Java 数据库主键生成类 IdWorker

    public synchronized long nextId() { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { this.sequence = (this.sequence + 1) & this.sequenceMask; if (this.sequence == 0) { System....

    线程间通信

    public synchronized void put(String name,String sex){ this.name=name; try{ Thread.sleep(10); }catch(Exception e){ System.out.println(e.getMessage()); } this....

    java—多线程的通信、生产者与消费者模式

    run方法是不能用synchronized修饰,他是继承来的,不能改变其结构,而且,如果run方法加了synchronized,就变成单线程了,就没有并发了。 只要不是静态的同步方法,同步方法默认的同步监视器就是this。 静态的同步...

Global site tag (gtag.js) - Google Analytics