java
首先创建一个学生资源类用来设置名字姓名:public class StudentDemo { String name; int age; boolean flag;}
创建一个设置的线程类:public class SetThread implements Runnable { private StudentDemo s; private int x = 0; public SetThread(StudentDemo s) { this.s = s; } @Override public void run() { while(true) { synchronized(s)//要用同一把锁! { //这里使用等待唤醒机制,使得线程能够依次运行! if(s.flag) { try { s.wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(x%2 == 0) { s.name = 'zhangsan'; s.age = 21; }else { s.name = 'lisi'; s.age = 18; } x++; s.flag = true; s.notify(); } } }}
创建一个获取的线程类:public class GetThread implements Runnable { private StudentDemo s; public GetThread(StudentDemo s) { this.s = s; } @Override public void run() { while (true) { synchronized (s) { if(!s.flag) { try { s.wait();//t2就被等待,同时释放锁,将来醒的时候就从这里开始执行! } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } System.out.println(s.name + '----' + s.age); s.flag = false; s.notify(); } } }}
注意:在加synchronized锁的时候,Set和Get里的必须使用同一把锁,要不然就没有意义了!
运行结果:lisi----18zhangsan----21lisi----18zhangsan----21lisi----18zhangsan----21lisi----18zhangsan----21lisi----18zhangsan----21lisi----18zhangsan----21lisi----18zhangsan----21...