1 public class Noodle { 2 String noodle; 3 String seasoning; 4 boolean flag = false; 5 } 6 7 8 public class Cook extends Thread { 9 10 private Noodle noodle; 11 12 public Cook(Noodle noodle) { 13 this.noodle = noodle; 14 } 15 16 @Override 17 public void run() { 18 int count = 0; 19 while (true) { 20 synchronized (noodle) { 21 if (noodle.flag == true) { 22 try { 23 noodle.wait(); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } 27 } 28 29 System.out.println("Cooker start cook noodles !"); 30 if (count % 2 == 0) { 31 noodle.noodle = "粗面"; 32 noodle.seasoning = "牛肉"; 33 } else { 34 noodle.noodle = "细面"; 35 noodle.seasoning = "脆臊"; 36 } 37 count ++; 38 System.out.println(noodle.seasoning + noodle.noodle); 39 40 try { 41 Thread.sleep(3000); 42 } catch (InterruptedException e) { 43 e.printStackTrace(); 44 } 45 noodle.flag = true; 46 noodle.notify(); 47 System.out.println("ready eat noodles !" + noodle.seasoning + noodle.noodle); 48 } 49 50 51 } 52 } 53 } 54 55 56 57 public class Customer extends Thread { 58 59 private Noodle noodle; 60 61 public Customer(Noodle noodle) { 62 this.noodle = noodle; 63 } 64 65 @Override 66 public void run() { 67 while (true) { 68 synchronized (noodle) { 69 if (noodle.flag == false) { 70 try { 71 noodle.wait(); 72 } catch (InterruptedException e) { 73 e.printStackTrace(); 74 } 75 } 76 System.out.println("start eat nooodles !"); 77 System.out.println(noodle.seasoning + noodle.noodle); 78 noodle.flag = false; 79 noodle.notify(); 80 System.out.println("noodles none ..."); 81 } 82 } 83 } 84 } 85 86 87 88 public class TheadTest { 89 90 public static void main(String[] args) { 91 Noodle noodle = new Noodle(); 92 new Cook(noodle).start(); 93 new Customer(noodle).start(); 94 } 95 96 }
线程池
原文:https://www.cnblogs.com/neoo9901/p/13717930.html