线程等待通知报错:代码如下:
import java.util.Timer;
import java.util.TimerTask;public class ThreadA extends Thread {
public static Calculator calculator = new Calculator(); public ThreadA(Calculator c) {
this.calculator = c;
} public void run() {
synchronized (calculator) {
try {
System.out.println(Thread.currentThread() + "等待计算结果");
calculator.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "11111111");
}
} public static void main(String[] args) {
Timer timer2=new Timer();
timer2.schedule(new TimerTask() {
public void run() {
synchronized (this) {
System.out.println("88888888");
}
System.out.println("777777777");
this.notifyAll();
System.out.println("777777777");//通知所有在此对象上等待的线程
}
},3000);
new ThreadA(calculator).start();
new ThreadA(calculator).start();
new ThreadA(calculator).start();
//启动计算线程
try{
Thread.sleep(6000);
}catch(InterruptedException e){
}
calculator.start();
}
}
class Calculator extends Thread {
public void run() {
synchronized (this) {
}
//通知所有在此对象上等待的线程
notifyAll();
}
}报错:Exception in thread "Timer-0"
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.notifyAll(Native Method)
at ThreadA$1.run(ThreadA.java:31)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
请问怎么解决???谢了
import java.util.Timer;
import java.util.TimerTask;public class ThreadA extends Thread {
public static Calculator calculator = new Calculator(); public ThreadA(Calculator c) {
this.calculator = c;
} public void run() {
synchronized (calculator) {
try {
System.out.println(Thread.currentThread() + "等待计算结果");
calculator.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "11111111");
}
} public static void main(String[] args) {
Timer timer2=new Timer();
timer2.schedule(new TimerTask() {
public void run() {
synchronized (this) {
System.out.println("88888888");
}
System.out.println("777777777");
this.notifyAll();
System.out.println("777777777");//通知所有在此对象上等待的线程
}
},3000);
new ThreadA(calculator).start();
new ThreadA(calculator).start();
new ThreadA(calculator).start();
//启动计算线程
try{
Thread.sleep(6000);
}catch(InterruptedException e){
}
calculator.start();
}
}
class Calculator extends Thread {
public void run() {
synchronized (this) {
}
//通知所有在此对象上等待的线程
notifyAll();
}
}报错:Exception in thread "Timer-0"
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.notifyAll(Native Method)
at ThreadA$1.run(ThreadA.java:31)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
请问怎么解决???谢了
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货