synchronized(this) vs synchronized(Class)

2486 ワード

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");
			
		}
		
	}
	
}