多线程案例_循环打印_设计4个线程...
要求:设计4个线程,其中两个线程每次对 i 增加1,另外两个线程对 i 每次减少1,写出程序。
在以下程序中,numOfPrint 代表题目中的 i
为了解决本方唤醒其他一方的问题。可以一个锁创建多个监视器对象(Condition对象)。
1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.Lock; 3 import java.util.concurrent.locks.ReentrantLock; 4 5 /** 6 * @author 馬建超 2018年1月19日 上午11:45:39 7 */ 8 public class ThreadTest6 { 9 public static void main(String[] args) { 10 final NumberIncreate ni = new NumberIncreate(); 11 new Thread(new Runnable() { 12 13 @Override 14 public void run() { 15 for (int i = 0; i < 5; i++) { 16 ni.num(); 17 } 18 19 } 20 }, "A").start(); 21 new Thread(new Runnable() { 22 23 @Override 24 public void run() { 25 for (int i = 0; i < 5; i++) { 26 ni.num2(); 27 } 28 29 } 30 }, "B").start(); 31 new Thread(new Runnable() { 32 33 @Override 34 public void run() { 35 for (int i = 0; i < 5; i++) { 36 ni.num3(); 37 } 38 39 } 40 }, "C").start(); 41 new Thread(new Runnable() { 42 43 @Override 44 public void run() { 45 for (int i = 0; i < 5; i++) { 46 ni.num4(); 47 } 48 49 } 50 }, "D").start(); 51 } 52 53 } 54 55 class NumberIncreate { 56 private int num = 1;// 当前正在执行线程的标记 57 private int numOfPrint = 0;// 打印的数字 58 private Lock lock = new ReentrantLock(); 59 Condition condition = lock.newCondition(); 60 Condition condition2 = lock.newCondition(); 61 Condition condition3 = lock.newCondition(); 62 Condition condition4 = lock.newCondition(); 63 64 public void num() { 65 lock.lock(); 66 try { 67 if (num != 1) { 68 condition.await(); 69 } 70 System.out.println("numOfPrint==" + numOfPrint++); 71 num = 2; 72 condition2.signal(); 73 } catch (Exception e) { 74 } finally { 75 lock.unlock(); 76 } 77 78 } 79 80 public void num2() { 81 lock.lock(); 82 try { 83 if (num != 2) { 84 condition2.await(); 85 } 86 System.out.println("numOfPrint==" + numOfPrint++); 87 num = 3; 88 condition3.signal(); 89 } catch (Exception e) { 90 } finally { 91 lock.unlock(); 92 } 93 94 } 95 96 public void num3() { 97 lock.lock(); 98 try { 99 if (num != 3) { 100 condition3.await(); 101 } 102 System.out.println("numOfPrint==" + numOfPrint--); 103 num = 4; 104 condition4.signal(); 105 } catch (Exception e) { 106 } finally { 107 lock.unlock(); 108 } 109 110 } 111 112 public void num4() { 113 lock.lock(); 114 try { 115 if (num != 4) { 116 condition4.await(); 117 } 118 System.out.println("numOfPrint==" + numOfPrint--); 119 num = 1; 120 condition.signal(); 121 } catch (Exception e) { 122 } finally { 123 lock.unlock(); 124 } 125 126 } 127 }
纸上学来终觉浅,觉知此事需躬行