问题在注释处
- public class WaitNotify {
- public static void main(String[] args) {
- Stu s=new Stu();
- WriteInfo w=new WriteInfo(s);
- ReadInfo r=new ReadInfo(s);
- Thread t1=new Thread(w);
- Thread t2=new Thread(r);
- t1.start();
- t2.start();
- }
- }
- class Stu{
- String name;
- int age;
- boolean flag=false;
- }
- class WriteInfo implements Runnable{
- private Stu s;
- int num=0;
- WriteInfo(Stu s){
- this.s=s;
- }
- public void run() {
- while(true){
- synchronized(Stu.class){ //为什么换成r就没有问题了???
- if(s.flag){
- try {
- s.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(num==0){
- s.name="李";
- s.age=20;
- }else{
- s.name="li";
- s.age=13;
- }
- num=(num+1)%2;
- s.flag=true;
- s.notify();
- }
- }
- }
- }
- class ReadInfo implements Runnable{
- private Stu s;
- ReadInfo(Stu s){
- this.s=s;
- }
- public void run() {
- while(true){
- synchronized(Stu.class){ //为什么换成r就没问题了???
- if(!s.flag){
- try {
- s.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println(s.name+s.age);
- s.flag=false;
- s.notify();
- }
- }
- }
- }
复制代码 |
|