线程同步synchronized

package com.aaa;

public class Person  extends Thread{
    
    
    private WC wc;
    
    public Person(WC wc){
        this.wc = wc;
    }
    
    public void run(){
        
        System.out.println(Thread.currentThread().getName()+"准备进行WC");
        wc.wc();
        System.out.println(Thread.currentThread().getName()+"走出了WC");
        
    }
    
    
    public static void main(String[] args) {
        
        WC wc = new WC();
        
        Person p0 = new Person(wc);
        
        Person p1 = new Person(wc);
        
        Person p2 = new Person(wc);
        
        p0.setName("---周泊臣----");
        p1.setName("---------躺一会------------");
        p2.setName("-------------------马德基--------------------");
        
        p0.start();
        p1.start();
        p2.start();
    }

}
package com.aaa;

public class WC {

    // 当发现同一个资源多个用户访问的时候会出现问题,这个时候请设置该 资源同步
    public 
//    synchronized  // 1.方法,在方法前使用同步关键字
    void wc() {

        // 2.使用同步块:好处是,可以使方法中的部分代码同步

        synchronized (this) {

            System.out.println(Thread.currentThread().getName() + "正在上WC");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "上完了WC");
        }
    }

}

 

posted @ 2012-10-19 12:03  邹晟  阅读(113)  评论(0编辑  收藏  举报