1. 程式人生 > >三個線程輪流打印1-75,一個線程一次打印5個數

三個線程輪流打印1-75,一個線程一次打印5個數

err trac main 修改 其他 number oid type i++

創建一個線程對應的類型,三個線程分開處理。

分別調用三個不同的線程,循環打印5個數字,打印完以後喚醒其他休眠的線程,然後自己休眠。

 1 package Thread;
 2 /**
 3  * 三個線程輪流打印1-75,一個線程一次打印5個數
 4  * @author Administrator
 5  *
 6  */
 7 
 8 public class ThreadDemo {
 9     //線程對應的類型,三個線程分開處理
10     static int type = 1;
11     static int number = 1;
12     public static void
main(String[] args) { 13 new Thread("第一個線程:") { // 創建一個線程,命名為第一個線程 14 public void run() { 15 try { 16 synchronized (ThreadDemo.class) { 17 while (number <= 75) { 18 //當type的值為1的時候,由第一個線程來打印 19
if (type == 1) { 20 for (int i = 0; i < 5; i++) { 21 System.out.println(Thread.currentThread().getName() + ":" + number++); 22 } 23 //修改類型值 24
type = 2; 25 //喚醒其他進入休眠的線程 26 ThreadDemo.class.notifyAll(); 27 //當前線程執行完進入休眠狀態 28 ThreadDemo.class.wait(); 29 } else { 30 ThreadDemo.class.wait(); 31 } 32 } 33 } 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 }; 38 }.start(); 39 new Thread("第二個線程:") { // 創建二個線程,命名為第一個線程 40 public void run() { 41 try { 42 synchronized (ThreadDemo.class) { 43 while (number <= 75) { 44 if (type == 2) { 45 for (int i = 0; i < 5; i++) { 46 System.out.println(Thread.currentThread().getName() + ":" + number++); 47 } 48 type = 3; 49 ThreadDemo.class.notifyAll(); 50 ThreadDemo.class.wait(); 51 } else { 52 ThreadDemo.class.wait(); 53 } 54 } 55 } 56 } catch (InterruptedException e) { 57 e.printStackTrace(); 58 } 59 }; 60 }.start(); 61 new Thread("第三個線程:") { // 創建三個線程,命名為第一個線程 62 public void run() { 63 try { 64 synchronized (ThreadDemo.class) { 65 while (number <= 75) { 66 if (type == 3) { 67 for (int i = 0; i < 5; i++) { 68 System.out.println(Thread.currentThread().getName() + ":" + number++); 69 } 70 type = 1; 71 ThreadDemo.class.notifyAll(); 72 if (number < 76) 73 ; 74 ThreadDemo.class.wait(); 75 } else { 76 ThreadDemo.class.wait(); 77 } 78 } 79 } 80 } catch (InterruptedException e) { 81 e.printStackTrace(); 82 } 83 }; 84 }.start(); 85 } 86 }

三個線程輪流打印1-75,一個線程一次打印5個數