线程引发非法监视器状态异常

时间:2019-07-07 13:05:47

标签: java multithreading

我正在学习线程。 以下程序抛出错误:

class myTask implements Runnable
{
	int a;
	int b;
	int sum;
	
	public myTask(int a, int b) {
		this.a = a;
		this.b = b;
	}
	
	public int getSum() throws InterruptedException {
		this.wait();
		System.out.println("getSum");
		return sum;
	}

	@Override
	public void run() {
		sum = a + b;
		this.notifyAll();
		System.out.println("In run");
	}	
	
}

public class ThreadExample {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		   
		
		myTask task = new myTask(4,3);
		
	    Thread t1 = new Thread(task);	    
	    t1.start();
	    
	    
	    System.out.println("Sum = " + task.getSum());
	}

}

以下是我得到的错误:

Exception in thread "main" Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at com.mastercard.codetest.jerseystore.file.myTask.getSum(ThreadExample.java:18)
    at com.mastercard.codetest.jerseystore.file.ThreadExample.main(ThreadExample.java:46)
java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at com.mastercard.codetest.jerseystore.file.myTask.run(ThreadExample.java:27)
    at java.lang.Thread.run(Thread.java:748)

我是Java线程的新手。我只是不明白为什么会出现错误。我认为我没有做错任何事情。

0 个答案:

没有答案