我创建了两个进程read和write,先让write阻塞,read运行两次后用notify()唤醒write,自己阻塞
就这样交替进行4次以后,退出.
可是我运行的结果就只有两次read,然后就死掉不动了
原代码:
class CommunityDemo implements Runnable
{
int time = 0; public CommunityDemo()
{
Thread thread1 = new Thread(this,"read");
Thread thread2 = new Thread(this,"write"); thread1.start();
thread2.start();
} public void run()
{
Thread t = Thread.currentThread();
try
{
if(!t.getName().equals("read"))
{
synchronized(this)
{
wait();
}
} while(true)
{
System.out.println(t.getName() + "rnnining");
time ++; if(time % 2 ==0)
{
synchronized(this)
{
System.out.println("........................................");
notify();
if(time == 8) break;
wait();
}
}
}
}
catch(Exception e)
{
} }
public static void main(String[] args)
{
CommunityDemo com = new CommunityDemo();;
}
}结果:
readrnnining
readrnnining
........................................
就这样交替进行4次以后,退出.
可是我运行的结果就只有两次read,然后就死掉不动了
原代码:
class CommunityDemo implements Runnable
{
int time = 0; public CommunityDemo()
{
Thread thread1 = new Thread(this,"read");
Thread thread2 = new Thread(this,"write"); thread1.start();
thread2.start();
} public void run()
{
Thread t = Thread.currentThread();
try
{
if(!t.getName().equals("read"))
{
synchronized(this)
{
wait();
}
} while(true)
{
System.out.println(t.getName() + "rnnining");
time ++; if(time % 2 ==0)
{
synchronized(this)
{
System.out.println("........................................");
notify();
if(time == 8) break;
wait();
}
}
}
}
catch(Exception e)
{
} }
public static void main(String[] args)
{
CommunityDemo com = new CommunityDemo();;
}
}结果:
readrnnining
readrnnining
........................................
{
System.out.println("........................................");
notify();//这里需要对另一个线程操作
if(time == 8) break;
wait();
}
什么意思,是要再加些什么代码吗?
请帮忙~~
{
Thread thread1 = new Thread(this,"read");
Thread thread2 = new Thread(this,"write");thread1.start();
thread2.start();
}public void run()
{
Thread t = Thread.currentThread();
try
{
if(!t.getName().equals("read"))
{
synchronized(this)
{
notify(); <<-----------------这里加上这一句就OK了,否则两个线程都处于挂起状态
wait();
}
}