转自:https://www.cnblogs.com/luozhijun/p/6895455.html
1. 要打印的资源
1 package com.mytest.thread; 2 3 /** 4 * 要打印的资源 5 * 6 */ 7 public class Num { 8 int i = 1; 9 // 两个线程看, 交替执行的一个标志 10 boolean flag = false; 11 }
2. 打印奇数的线程
1 package com.mytest.thread; 2 3 public class PrintOdd implements Runnable { 4 Num num; 5 6 public PrintOdd(Num num) { 7 this.num = num; 8 9 } 10 11 public void run() { 12 while (num.i <= 100) { 13 synchronized (num) { 14 if (num.flag) { 15 try { 16 num.wait(); 17 } catch (Exception e) { 18 System.out.println(e.getMessage()); 19 } 20 21 } else { 22 System.out.println("奇数----" + num.i); 23 num.i++; 24 num.flag = true; 25 num.notify(); 26 } 27 28 } 29 } 30 } 31 }
3. 打印偶数的线程
1 package com.mytest.thread; 2 3 public class PrintEven implements Runnable { 4 5 Num num; 6 7 public PrintEven(Num num) { 8 this.num = num; 9 10 } 11 12 public void run() { 13 while (num.i <= 100) { 14 synchronized (num) {// 必须要用同意吧锁对象,这个对象是num 15 if (!num.flag) { 16 try { 17 num.wait();// wait()函数必须和锁死同一个 18 } catch (Exception e) { 19 System.out.println(e.getMessage()); 20 } 21 22 } else { 23 System.out.println("偶数----" + num.i); 24 num.i++; 25 num.flag = false; 26 num.notify(); 27 } 28 29 } 30 } 31 } 32 33 }
4. 主函数
1 package com.mytest.thread; 2 3 public class Main { 4 public static void main(String[] args) { 5 6 Num num = new Num(); 7 8 PrintOdd printOdd = new PrintOdd(num); 9 PrintEven printEven = new PrintEven(num); 10 11 Thread thread1 = new Thread(printOdd); 12 Thread thread2 = new Thread(printEven); 13 14 thread1.start(); 15 thread2.start(); 16 } 17 }
5. 运行结果