java-多线程-同步的优化
1 package test; 2 3 public class Test01{ 4 public static void main(String[] args) { 5 Student s=new Student(); 6 7 SetThread st=new SetThread(s); 8 GetThread gt=new GetThread(s); 9 10 Thread t1=new Thread(st); 11 Thread t2=new Thread(gt); 12 13 t1.start(); 14 t2.start(); 15 } 16 }
1 package test; 2 3 public class Student { 4 private String name; 5 private int age; 6 private boolean flag; //默认是false; 7 8 public synchronized void set(String name,int age){ 9 //如果有数据,等待 10 if(this.flag){ 11 try { 12 this.wait(); 13 } catch (InterruptedException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } 17 } 18 //设置数据 19 this.name=name; 20 this.age=age; 21 //修改标记 22 this.flag=true; 23 this.notify(); 24 } 25 public synchronized void get(){ 26 if(!this.flag){ 27 try { 28 this.wait(); 29 } catch (InterruptedException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 } 34 System.out.println(this.name+"---"+this.age); 35 //修改标记 36 this.flag=false; 37 this.notify(); 38 } 39 }
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 if (x % 2 == 0) { 15 s.set("hello", 22); 16 } else { 17 s.set("来了", 10); 18 } 19 x++; 20 } 21 22 } 23 }
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 10 @Override 11 public void run() { 12 // TODO Auto-generated method stub 13 while (true) { 14 s.get(); 15 } 16 17 } 18 }