多线程循环打印123
1、多线程循环打印123
使用waite notify的标准范式,并发编程的艺术,4.3.3
public class Test2 { private static Object object = new Object(); private static int flag = 1; public static void main(String[] args) { for (int i = 0; i < 6; i++) { Print1 print1 = new Print1(); print1.start(); Print2 print2 = new Print2(); print2.start(); Print3 print3 = new Print3(); print3.start(); } } static class Print1 extends Thread { @Override public void run() { synchronized (object) { while (flag != 1) { try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(1); flag = 2; object.notifyAll(); } } } static class Print2 extends Thread { @Override public void run() { synchronized (object) { while (flag != 2) { try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(2); flag = 3; object.notifyAll(); } } } static class Print3 extends Thread { @Override public void run() { synchronized (object) { while (flag != 3) { try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(3); flag = 1; object.notifyAll(); } } } }
。。。
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PrintThread { private Lock lock = new ReentrantLock(); private volatile int flag = 1; // 控制执行哪个线程 private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public static void main(String[] args) { PrintThread printThread = new PrintThread(); for (int i = 0; i < 10; i++) { new Thread(() -> printThread.printA(), "A").start(); new Thread(() -> printThread.printB(), "B").start(); new Thread(() -> printThread.printC(), "C").start(); } } public void printA() { lock.lock(); try { while (flag != 1) { condition1.await(); } System.out.println(Thread.currentThread().getName() + " : 1"); flag = 2; condition1.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB() { lock.lock(); try { while (flag != 2) { condition2.await(); } System.out.println(Thread.currentThread().getName() + " : 2"); flag = 3; condition2.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC() { lock.lock(); try { while (flag != 3) { condition3.await(); } System.out.println(Thread.currentThread().getName() + " : 3"); flag = 1; condition3.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
。。。