三个多线程的交替打印

三个多线程的交替打印
文章图片
三个多线程的交替打印
文章图片

1 package cn.thread; 2 3 public class ManyThread2 { 4public static void main(String[] args) { 5MyRunnable1 runnable1 = new MyRunnable1(); 6MyRunnable2 runnable2 = new MyRunnable2(); 7MyRunnable3 runnable3 = new MyRunnable3(); 8 9Thread t1 = new Thread(runnable1, "线程1"); 10Thread t2 = new Thread(runnable2, "线程2"); 11Thread t3 = new Thread(runnable3, "线程3"); 12 13t1.start(); 14t2.start(); 15t3.start(); 16} 17 } 18 19 class Print { 20public static int count = 0; 21public static Object obj = new Object(); 22public static int x = 1; 23 24public static void print1(int i) { 25synchronized (obj) { 26if (x == 1) { 27for (int j = 0; j < 5; j++) { 28count++; 29System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i); 30} 31x = 2; 32try { 33Thread.sleep(200); 34} catch (InterruptedException e) { 35e.printStackTrace(); 36} 37obj.notifyAll(); 38} else { 39try { 40obj.wait(); 41} catch (InterruptedException e) { 42e.printStackTrace(); 43} 44} 45} 46} 47 48public static void print2(int i) { 49synchronized (obj) { 50if (x == 2) { 51for (int j = 0; j < 5; j++) { 52count++; 53System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i); 54} 55x = 3; 56try { 57Thread.sleep(200); 58} catch (InterruptedException e) { 59e.printStackTrace(); 60} 61obj.notifyAll(); 62} else { 63try { 64obj.wait(); 65} catch (InterruptedException e) { 66e.printStackTrace(); 67} 68} 69} 70} 71 72public static void print3(int i) { 73synchronized (obj) { 74if (x == 3) { 75for (int j = 0; j < 5; j++) { 76count++; 77System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i); 78} 79x = 1; 80try { 81Thread.sleep(200); 82} catch (InterruptedException e) { 83e.printStackTrace(); 84} 85obj.notifyAll(); 86} else { 87try { 88obj.wait(); 89} catch (InterruptedException e) { 90e.printStackTrace(); 91} 92} 93} 94} 95 } 96 97 class MyRunnable1 implements Runnable { 98@Override 99public void run() { 100for (int i = 0; i < 10; i++) { 101if (Print.count <= 55) { 102Print.print1(i); 103} 104} 105} 106 } 107 108 class MyRunnable2 implements Runnable { 109@Override 110public void run() { 111for (int i = 0; i < 10; i++) { 112if (Print.count <= 55) { 113Print.print2(i); 114} 115} 116} 117 } 118 119 class MyRunnable3 implements Runnable { 120@Override 121public void run() { 122for (int i = 0; i < 10; i++) { 123if (Print.count < 50) { 124Print.print3(i); 125} 126} 127} 128 }

三个多线程的交替打印 【三个多线程的交替打印】
转载于:https://www.cnblogs.com/1020182600HENG/p/6044650.html

    推荐阅读