面试题——两个线程交替运行

 

/**
 * 两个线程交替进行
 * 
 * @author ChenSS 2017年7月27日下午8:05:08 
 */
class AlternatelyRunnable implements Runnable{
    private Object lock;
    
    public AlternatelyRunnable(Object lock) {
        this.lock=lock;
    }
    
    @Override
    public void run() {
        try {
            synchronized (lock) {
                for (int i = 0; i < 100; i++) {
                    lock.notify();
                    System.out.println(Thread.currentThread().getName() + i);
                    Thread.sleep(50);
                    lock.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Object lock = new Object();
        AlternatelyRunnable runnable=new AlternatelyRunnable(lock);
        Thread threada = new Thread(runnable,"A : ");
        Thread threadb = new Thread(runnable,"B : ");
        threada.start();
        threadb.start();
    }
}

 

posted on 2017-07-27 20:08  疯狂的妞妞  阅读(146)  评论(0编辑  收藏  举报

导航