sychronized反発ロック(学習ノート)

1043 ワード

sychronized
/**
 *    
 * sychronized  :            
 *       ,                        
 *                    
 * @author zhaxi
 */
public class SychronizedDemo {

	public static void main(String[] args) {
		final SychronizedDemo sd = new SychronizedDemo() ;
		Thread a = new Thread(){
				public void run(){
					sd.threadA();
				}
		} ;

		Thread b = new Thread(){
			public void run(){
				sd.threadB();
			}
		} ;
		
		a.start() ;
		b.start() ;
	}
	
	//1、               
	//2、   b            a   
	public synchronized void threadA(){
		
		try {
			Thread th = Thread.currentThread() ;
			System.out.println(th.getName()+"  a   ..") ;
			Thread.sleep(1000);
			System.out.println(th.getName()+"  a    ") ;
		} catch (Exception e) {
		}
		
	}

	public synchronized void threadB(){
		try {
			Thread th = Thread.currentThread() ;
			System.out.println(th.getName()+"  b   ..") ;
			Thread.sleep(1000);
			System.out.println(th.getName()+"  b    ") ;
		} catch (Exception e) {
		}
	}
}