面试题——两个线程交替运行
/** * 两个线程交替进行 * * @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(); } }
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!