|
| 1 | +# Java |
| 2 | + |
| 3 | +两个交替打印数字 |
| 4 | + |
| 5 | +```java |
| 6 | +package src.MultiThreading.AlternatePrint; |
| 7 | + |
| 8 | + |
| 9 | +public class AP1 { |
| 10 | + |
| 11 | + private static int num = 0; |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + Object lock = new Object(); |
| 15 | + Thread thread1 = new Thread(() -> { |
| 16 | + while(true){ |
| 17 | + synchronized (lock){ |
| 18 | + lock.notify(); |
| 19 | + System.out.println("THREAD1 " + num++); |
| 20 | + try { |
| 21 | + Thread.sleep(1000); |
| 22 | + lock.wait(); |
| 23 | + } catch (InterruptedException e) { |
| 24 | + throw new RuntimeException(e); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + }); |
| 29 | + Thread thread2 = new Thread(() -> { |
| 30 | + while(true){ |
| 31 | + synchronized (lock){ |
| 32 | + lock.notify(); |
| 33 | + System.out.println("THREAD2 " + num++); |
| 34 | + try { |
| 35 | + Thread.sleep(1000); |
| 36 | + lock.wait(); |
| 37 | + } catch (InterruptedException e) { |
| 38 | + throw new RuntimeException(e); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + }); |
| 43 | + thread1.start(); |
| 44 | + thread2.start(); |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +三个线程交替打印 |
| 50 | + |
| 51 | +```java |
| 52 | +package src.MultiThreading.AlternatePrint; |
| 53 | + |
| 54 | +class ThreeThreadAP2 { |
| 55 | + |
| 56 | + |
| 57 | + private static int num = 0; |
| 58 | + |
| 59 | + private static Object lock = new Object(); |
| 60 | + |
| 61 | + |
| 62 | + public static void main(String[] args) { |
| 63 | + |
| 64 | + new Thread(() -> { |
| 65 | + while(true){ |
| 66 | + synchronized (lock){ |
| 67 | + if(num % 3 == 0){ |
| 68 | + lock.notifyAll(); |
| 69 | + System.out.println("Thread1 " + num++); |
| 70 | + try { |
| 71 | + Thread.sleep(1000); |
| 72 | + lock.wait(); |
| 73 | + } catch (InterruptedException e) { |
| 74 | + throw new RuntimeException(e); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + } |
| 79 | + } |
| 80 | + }).start(); |
| 81 | + new Thread(() -> { |
| 82 | + while(true){ |
| 83 | + synchronized (lock){ |
| 84 | + if(num % 3 == 1){ |
| 85 | + lock.notifyAll(); |
| 86 | + System.out.println("Thread2 " + num++); |
| 87 | + try { |
| 88 | + Thread.sleep(1000); |
| 89 | + lock.wait(); |
| 90 | + } catch (InterruptedException e) { |
| 91 | + throw new RuntimeException(e); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + }).start(); |
| 97 | + new Thread(() -> { |
| 98 | + while(true){ |
| 99 | + synchronized (lock){ |
| 100 | + if(num % 3 == 2){ |
| 101 | + lock.notifyAll(); |
| 102 | + System.out.println("Thread3 " + num++); |
| 103 | + try { |
| 104 | + Thread.sleep(1000); |
| 105 | + lock.wait(); |
| 106 | + } catch (InterruptedException e) { |
| 107 | + throw new RuntimeException(e); |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + }).start(); |
| 113 | + } |
| 114 | +} |
| 115 | +``` |
| 116 | + |
0 commit comments