public class WaitComm {
public static void main(String[] args) {
WFlagSend s = new WFlagSend();
WFlagRec r = new WFlagRec(s);
Thread st = new Thread(s);
Thread rt = new Thread(r);
rt.setDaemon(true);
st.start();
rt.start();
try {
st.join();
while ( s.isValid ){
Thread.sleep(100);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}class WFlagSend implements Runnable {
int theValue;
boolean isValid = false;
public void run() {
for ( int i=0; i<5; i++){
synchronized(this){
while (isValid){
try{
this.wait();
}catch(Exception e){e.printStackTrace();}
}
}
theValue = (int)(Math.random()*256);
System.out.println("sending " + theValue );
synchronized(this){
isValid = true;
this.notify();
}
}
}
}class WFlagRec implements Runnable {
private WFlagSend theSender;
public WFlagRec(WFlagSend sender){
theSender = sender;
}
public void run() {
while ( true ) {
synchronized(theSender) {
while ( !theSender.isValid ){
try{
theSender.wait();
}catch(Exception e){e.printStackTrace();}
}
}
System.out.println("received " + theSender.theValue);
synchronized(theSender) {
theSender.isValid = false;
theSender.notify();
}
}
}
}这就是这个不怎么理解,请大家指点下呀
public static void main(String[] args) {
WFlagSend s = new WFlagSend();
WFlagRec r = new WFlagRec(s);
Thread st = new Thread(s);
Thread rt = new Thread(r);
rt.setDaemon(true);
st.start();
rt.start();
try {
st.join();
while ( s.isValid ){
Thread.sleep(100);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}class WFlagSend implements Runnable {
int theValue;
boolean isValid = false;
public void run() {
for ( int i=0; i<5; i++){
synchronized(this){
while (isValid){
try{
this.wait();
}catch(Exception e){e.printStackTrace();}
}
}
theValue = (int)(Math.random()*256);
System.out.println("sending " + theValue );
synchronized(this){
isValid = true;
this.notify();
}
}
}
}class WFlagRec implements Runnable {
private WFlagSend theSender;
public WFlagRec(WFlagSend sender){
theSender = sender;
}
public void run() {
while ( true ) {
synchronized(theSender) {
while ( !theSender.isValid ){
try{
theSender.wait();
}catch(Exception e){e.printStackTrace();}
}
}
System.out.println("received " + theSender.theValue);
synchronized(theSender) {
theSender.isValid = false;
theSender.notify();
}
}
}
}这就是这个不怎么理解,请大家指点下呀
解决方案 »
- 谁可以帮我解决一下关于javadoc的问题
- 关于setColor的问题,颜色一下子就没有了,怎么回事
- mysql连接问题
- 急救~~~~~怎么用url类实现访问带session的两个页面?????????
- 菜鸟的问题:怎么能看到小应用程序的源代码啊?新手上路!
- main()中命令行參數的使用問題
- 请教各位数据结构(java)高手
- 我的源程序怎么无法编译?
- * * * * * * * * * * 客观评价,VJ++有哪些不好,哪些好? * * * * * * * * * *
- 有谁开发过手机上的应用,我下了个Jbuilder MobileSet ,请告诉我序列号和密码。
- 如何画出正态分布图
- 有关输入输出流问题
使其运行
st.join(); 表示当前线程必须等待线程st运行完以后才可以继续运行