有关线程的问题,请指教!
public class TwoThread
{
private static class TestThread extends Thread
{
public TestThread(String s)
{
super(s);
}
public void run()
{
TestThread t=( TestThread )Thread.currentThread();
try{
if (!t.getName().equalsIgnoreCase("one"))
{
synchronized(this)
{
wait();
}
}
int i=0;
for(i=0; i<10;i++)
{
System.out.println(this.getName()+" i= "+i);
}
synchronized(this)
{
notify();
wait();
}
for(i=10;i<20;i++)
{
System.out.println(this.getName()+" i= "+i);
}
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
public static void main(String args[])
{
TestThread one=new TestThread("one");
TestThread two=new TestThread("two");
one.start();
two.start();
}
}
我的程序的目的是先让线程one执行,线程two等待,one输出从0到9的数后,唤醒two,one等待,two输出0到9的数后再唤醒one,执行后面的代码。
但是实际执行的结果如下:
D:\>java TwoThread
one i= 0
one i= 1
one i= 2
one i= 3
one i= 4
one i= 5
one i= 6
one i= 7
one i= 8
one i= 9
one输出0到9的数后,程序就没反应了,这是怎么回事?怎么修改,请指教!
问题点数:80、回复次数:8Top
1 楼yangjun2(华灯初上)回复于 2003-05-03 10:34:44 得分 0
wait();---->wait(500);Top
2 楼lindianxuan(tention)回复于 2003-05-03 11:18:21 得分 0
把第二个wait()去掉,或加上判断Top
3 楼theninthsky(第九天)回复于 2003-05-03 11:23:37 得分 20
将第一个wait()改为wait(500)
将第二个wait()改为wait(600)
输出结果:one从1-9,two 从1-9,one 从10-19,two从10-19Top
4 楼theninthsky(第九天)回复于 2003-05-03 11:27:32 得分 0
to lindianxuan(海之都)
去掉第二个wait()就不对了,输出结果:one 从1-19,不再输出twoTop
5 楼amjn(神雕过儿)回复于 2003-05-03 12:30:26 得分 0
你这两个线程好像不是基于一个对象吧Top
6 楼amjn(神雕过儿)回复于 2003-05-03 12:30:41 得分 60
package test52;
public class Test52 {
private static class TestThread extends Thread{
public void run(){
if(!Thread.currentThread().getName().equalsIgnoreCase("One")){
synchronized(this){
try{
wait();
}
catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
}
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+": i="+i);
}
synchronized(this){
notify();
try{
wait();
}
catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
for(int i=10;i<20;i++){
System.out.println(Thread.currentThread().getName()+": i="+i);
}
}
}
public static void main(String[] args){
TestThread test=new TestThread();
Thread one=new Thread(test,"One");
Thread two=new Thread(test,"Two");
one.start();
two.start();
}
}Top
7 楼yangjun2(华灯初上)回复于 2003-05-03 16:27:06 得分 0
synchronized(this){
notify(); ----- 放到执行队列里面
try{
wait(); ----又等待,这里不明白?
}
catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
我执行test52,好像不能运行成功哦。
Top
8 楼mutou1977(木头)回复于 2003-05-03 22:32:27 得分 0
to amjn(神雕过儿)
执行结果是:
D:\TempCode>java Test52
One: i=0
One: i=1
One: i=2
One: i=3
One: i=4
One: i=5
One: i=6
One: i=7
One: i=8
One: i=9
Two: i=0
Two: i=1
Two: i=2
Two: i=3
Two: i=4
Two: i=5
Two: i=6
Two: i=7
Two: i=8
Two: i=9
One: i=10
One: i=11
One: i=12
One: i=13
One: i=14
One: i=15
One: i=16
One: i=17
One: i=18
One: i=19
two的10-19输不出来。Top




