急,这个问题怎么解决?
代码如下:
public class testwait extends Thread{
public testwait() {
}
public void run() {
Thread c=this.currentThread();
class th extends Thread {
Thread cc;
public th()
{
}
public void getpar(Thread c)
{
cc=c;
}
public void run() {
while (true) {
synchronized (this) {
try {
this.wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("Sub");
try {
sleep(1000);
}
catch (Exception ex) {
ex.printStackTrace();
}
synchronized (cc) {
try {
cc.notify();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
this.yield();
}
}
};
th r=new th();
r.getpar(c);
r.start();
while (true) {
System.out.println("Main");
try {
sleep(1000);
}
catch (Exception ex) {
ex.printStackTrace();
}
synchronized (r) {
r.notify();
}
this.yield();
synchronized (this) {
try {
this.wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
testwait testwait1 = new testwait();
testwait1.start();
}
}
把两上sleep去掉就跑不起来,原因很简单,因为线程还没有被wait就已经notify了,所最后两个线程都在wait();
我觉得用sleep没意思,想问问各位有什么好主意没有?