实例-Leetcode并发编程
leetcode-1114 按序打印
leetcode只要 方法1 2 3顺序执行,我对其作了修改,1-2-3-1-2-3循环周期打印
通过两个volatile共享内存变量实现线程间信息交流。
当first和seconde都为false时,first里面的printFirst()才能执行,然后通知printSecond()方法可以执行了。
class Foo { void Foo(){ } volatile boolean first = false; volatile boolean second = false; public void first(Runnable printFirst) throws InterruptedException{ while (first || second) { } // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); first = true; } public void second(Runnable printSecond) throws InterruptedException{ while (!first) { } // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); second = true; } public void third(Runnable printThird) throws InterruptedException{ while (!second) { } // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); first = false; second = false; } }