黑马程序员技术交流社区
标题:
多线程交互问题
[打印本页]
作者:
张翼
时间:
2011-12-9 20:56
标题:
多线程交互问题
import java.util.*;
public class exercise
{
public static void main(String argv[])
{
Thread t1 = new Thread(new thread1());
Thread t2 = new Thread(new thread2());
t2.start();
t1.start();
}
}
class thread1 extends Thread
{
boolean option = true;
public void run()
{
while(option)
{
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
System.out.println(new Date());
}
}//run end
public void changeOption()
{
option = false;
}
}
class thread2 extends Thread
{
public void run()
{
thread1 t3 = new thread1();
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
t3.changeOption();
}
}
这段代码的目的是让时间显示,每隔一秒显示,但是只显示十秒内的时间,第十一秒程序便停止了,但是为什么一直显示下去,请问谁知道错在哪里?
作者:
唐秀启
时间:
2011-12-9 22:01
本帖最后由 benbenqi 于 2011-12-9 22:15 编辑
/*
显示系统时间,每一秒显示一次,共显示10s,第11s停止。
*/
import java.util.*;
public class Exercise
{
public static void main(String[] args)
{
ShowTime st = new ShowTime();
new Thread(st).start();
new Thread(st).start();
}
}
class ShowTime implements Runnable
{
private int i = 10;
public void run()
{
while(i!=0)
{
show();
}
}
public synchronized void show()
{
if(i>0)
{
try
{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"......"+new Date()+"...."+i--);
}
}
}
复制代码
有些部分我是为了增加显示效果 才加上去的。。。
兄弟自己测试下吧
如果你感觉效果不明显可以把i改成i<=1000, sleep(10),这样就明显了
作者:
◇半度微凉
时间:
2011-12-9 22:19
我把你这段代码放到我Myeclipse 里运行了一下!你这个之所以一直显示下去,是因为你那个changeOption()方法根本没被调用到,也可以说你最后那个thread2()根本没运行,那个t3.changeOption();也没有调用到changeOption()方法。所以, 程序运行后,option的值从始至终都是你开始初始化的true,所以 while(option)这个循环里面option一直为true,一直满足条件,所以就一直向下运行!
作者:
李明
时间:
2011-12-9 23:18
thread1 t3 = new thread1();建的对象和t1不是一个,所以t1的changeOption()根本调用不到,所以t1一直打印。
作者:
周敏2011nc
时间:
2011-12-21 16:42
解决方法 : static boolean option = true
你在thread2中从新new出了一个thread1的对象,它并不是你第一次new出来的thread1的对象,它们各自拥有一份thread1中的option变量,并不共享。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2