关于使用Thread.yield()进行线程通讯的问题
//代码1 package communication; import java.util.Random; public class Flag { public static void main(String[] args) { FlagSender f = new FlagSender(); FlagRec r = new FlagRec(f); Thread t1 = new Thread(f); Thread t2 = new Thread(r); t1.start(); t2.start(); } } class FlagSender implements Runnable{ private int theValue; private boolean flag; public int getTheValue() { return theValue; } public void setTheValue(int theValue) { this.theValue = theValue; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } @Override public void run() { for (int i = 0; i < 5; i++) { while(flag){ Thread.yield(); } theValue = new Random().nextInt(1000); System.out.println("send the value is "+theValue); flag = true; } } } class FlagRec implements Runnable{ private FlagSender f; public FlagRec(FlagSender f) { super(); this.f = f; } @Override public void run() { for (int i = 0; i < 5; i++) { while(!f.isFlag()){ Thread.yield(); } System.out.println("receive the value is "+f.getTheValue()); f.setFlag(false); } } }
//代码2 package communication; import java.util.Random; public class WrongOfFlag { public static void main(String[] args) { FlagSender1 f = new FlagSender1(); FlagRec1 r = new FlagRec1(); Thread t1 = new Thread(f); Thread t2 = new Thread(r); t1.start(); t2.start(); } } class FlagSender1 implements Runnable{ private int theValue; private boolean flag; public int getTheValue() { return theValue; } public void setTheValue(int theValue) { this.theValue = theValue; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } @Override public void run() { for (int i = 0; i < 5; i++) { while(flag){ Thread.yield(); } theValue = new Random().nextInt(1000); System.out.println("send the value is "+theValue); flag = true; } } } class FlagRec1 implements Runnable{ FlagSender f = new FlagSender(); @Override public void run() { for (int i = 0; i < 5; i++) { while(!f.isFlag()){ Thread.yield(); } System.out.println("receive the value is "+f.getTheValue()); f.setFlag(false); } } }
为什么要让FlagSender作为FlagRec的成员,像代码二中直接new了FlagSender为什么结果只输出一个send the value is 138,然后就死循环空程序了,结果如下图