刚刚看到JAVA线程控制这里,做了一个例子,这个郁闷啊~~
完全不知道join() yield() 这两个方法是做什么用的
请高手指点一下哈
辛苦辛苦啦例子如下
class FlagSend
implements Runnable {
volatile int theValue;
volatile boolean isValue; public void run() {
for (int i = 0; i < 5; i++) {
while (isValue) {
Thread.yield();
}
theValue = (int) (Math.random() * 100);
System.out.println("sending:" + theValue);
isValue = true;
}
}
} class FlagRec
implements Runnable {
FlagSend sendflag;
public FlagRec(FlagSend flagsend) {
sendflag = flagsend;
} public void run() {
while (true) {
while (!sendflag.isValue) {
Thread.yield();
}
System.out.println("received:" + sendflag.theValue);
sendflag.isValue = false;
}
}
} FlagSend s = new FlagSend();
FlagRec r = new FlagRec(s); Thread st = new Thread(s);
Thread rt = new Thread(r); st.start();
rt.start();
st.join();
try {
while (s.isValue) {
Thread.sleep(1000);
}
}
catch (InterruptedException ex) {
}
完全不知道join() yield() 这两个方法是做什么用的
请高手指点一下哈
辛苦辛苦啦例子如下
class FlagSend
implements Runnable {
volatile int theValue;
volatile boolean isValue; public void run() {
for (int i = 0; i < 5; i++) {
while (isValue) {
Thread.yield();
}
theValue = (int) (Math.random() * 100);
System.out.println("sending:" + theValue);
isValue = true;
}
}
} class FlagRec
implements Runnable {
FlagSend sendflag;
public FlagRec(FlagSend flagsend) {
sendflag = flagsend;
} public void run() {
while (true) {
while (!sendflag.isValue) {
Thread.yield();
}
System.out.println("received:" + sendflag.theValue);
sendflag.isValue = false;
}
}
} FlagSend s = new FlagSend();
FlagRec r = new FlagRec(s); Thread st = new Thread(s);
Thread rt = new Thread(r); st.start();
rt.start();
st.join();
try {
while (s.isValue) {
Thread.sleep(1000);
}
}
catch (InterruptedException ex) {
}
解决方案 »
- java 文件传输
- java中如何求两个日期之间的天数?
- 子类继承父类的private,只不过不能使用而已,内存里还是独立存在的....这句话对吗??
- Windows下用C++写的dll如何才能被Linux下的Java调用?
- 请问我的程序那里错了???
- jbuilder->exe文件的问题
- >>>>>>>>>>>>>>Tomcat4的问题,非常着急
- 用JAVA写了程序(application)之后,要在网上用,总不能让人家都装JDK吧,有什么好的办法
- 怎样得知db2数据库的端口号?
- 请问有谁知道一款叫着mocha的java反编译器?
- 关于SQL 的insert into values
- 讨论:大家都在使用JAVA做哪种开发模式?
1) sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。
2) sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。使调用join()的线程执行完毕后才能执行其它线程,在一定意义上,它可以实现同步的功能。
Thread1.join();
System.out.println("aaa");只有当Thread1执行完成之后
才能打印出来aaa?
对吗?
//也就是说
//Thread1.join();
//System.out.println("aaa");//只有当Thread1执行完成之后
//才能打印出来aaa?
//对吗?
可以这么说。
join():用于不同线程间的联系,当一个线程1调用另一个线程2的join()方法,那么线程1在线程2结束前就会被挂起(除非设置timeout)。由于也可以被interrupt()打断,所以也要放在try域中。