java-多线程4
等待唤醒机制
1 package test; 2 3 /* 4 * 生产者消费者问题 5 * 分析: 6 * 资源类:Student 7 * 设置学生数据:SetThread(生产者) 8 * 获取学生数据:GetThread(消费者) 9 * 测试类:Test01 10 * */ 11 12 public class Test01{ 13 public static void main(String[] args) { 14 Student s=new Student(); 15 16 SetThread st=new SetThread(s); 17 GetThread gt=new GetThread(s); 18 19 Thread t1=new Thread(st); 20 Thread t2=new Thread(gt); 21 22 t1.start(); 23 t2.start(); 24 } 25 }
1 package test; 2 3 public class Student { 4 String name; 5 int age; 6 boolean flag; //默认是false; 7 }
1 package test; 2 3 public class SetThread implements Runnable { 4 private Student s; 5 private int x = 0; 6 7 public SetThread(Student s) { 8 this.s = s; 9 } 10 11 @Override 12 public void run() { 13 while (true) { 14 // TODO Auto-generated method stub 15 synchronized (s) { 16 if(s.flag){ 17 try { 18 s.wait(); 19 } catch (InterruptedException e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } 23 } 24 if (x % 2 == 0) { 25 s.name = "hello"; 26 s.age = 22; 27 } else { 28 s.name = "龙头"; 29 s.age = 10; 30 } 31 x++; 32 33 s.flag=true; 34 s.notify(); 35 } 36 } 37 } 38 }
1 package test; 2 3 public class GetThread implements Runnable{ 4 private Student s; 5 6 public GetThread(Student s){ 7 this.s=s; 8 } 9 @Override 10 public void run() { 11 // TODO Auto-generated method stub 12 while(true){ 13 synchronized (s) { 14 if(!s.flag){ 15 try { 16 s.wait(); 17 } catch (InterruptedException e) { 18 // TODO Auto-generated catch block 19 e.printStackTrace(); 20 } 21 } 22 System.out.println(s.name + "--" + s.age); 23 s.flag=false; 24 s.notify(); 25 } 26 } 27 28 } 29 }