1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| package com.atzrh.多线程;
import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;
public class PrintNumberThree { public static ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1000, TimeUnit.SECONDS, new SynchronousQueue<>()); public final static ReentrantLock lock = new ReentrantLock(); public final static java.util.concurrent.locks.Condition c1 = lock.newCondition(); public final static java.util.concurrent.locks.Condition c2 = lock.newCondition(); public final static java.util.concurrent.locks.Condition c3 = lock.newCondition();
public static int num = 1;
public static void main(String[] args) { executor.execute(()->{ while (num<=100){ lock.lock(); c2.signal(); System.out.println(Thread.currentThread().getName()+":"+num); num++; try { c1.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } lock.unlock(); } });a executor.execute(()->{ while (num<=100){ lock.lock(); c3.signal(); System.out.println(Thread.currentThread().getName()+":"+num); num++; try { c2.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } lock.unlock(); } }); executor.execute(()->{ while (num<=100){ lock.lock(); c1.signal(); System.out.println(Thread.currentThread().getName()+":"+num); num++; try { c3.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } lock.unlock(); } }); } }
|