线程的问题,能否帮忙解释下整个过程以及wait(),notify()如何搭配的?
输出:
0
2
4
i am waiting...num==3
6
//代码如下
public class Test extends Thread {
private int num;
private boolean isComplete;
private int result;
public Test(int num) {
//标志线程名
super(String.valueOf(num));
this.num = num;
}
//
public synchronized void run() {
result = num * 2;
isComplete = true;
for (int i=0;i<100000;i++){
}
notify();
}
public synchronized int getResult() {
while (!isComplete) {
try {
System.out.println("i am waiting...num=="+num);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String args[]) {
Test[] tests = new Test[4];
for (int i = 0; i < tests.length; i++) {
tests[i] = new Test(i);
tests[i].start();
}
for (int i =0;i<tests.length;i++){
System.out.println(tests[i].getResult() + " ");
}
}
}
另外若getResult不加同步:
public int getResult() {
while (!isComplete) {
try {
System.out.println("i am waiting...num=="+num);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
为何输出:
i am waiting...num==0
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:429)
at testclass.scjp.Test.getResult(Test.java:48)
at testclass.scjp.Test.main(Test.java:64)
Exception in thread "main"
[解决办法]
你这个程序本身结果就是不确定的,你多运行几次会得到不同的结果。
首先创建一个线程数组tests,接着依次创建4个线程并启动,调用run()方法,但你要注意的是并不是调用完所有线程的run方法后再执行
for (int i =0;i <tests.length;i++){
System.out.println(tests[i].getResult() + " ");
}
程序段,另外notify()方法唤醒哪个线程也是由jvm决定的,这也存在不确定因素,所以有多种结果就不奇怪了。至于去掉synchronized方法后会报那个错误是因为,对于wait(),wait(long),notify(),notifyAll()等这些方法,只有在当前线程中才能使用,否则报运行时错误java.lang.IllegalMonitorStateException: current thread not owner.也就是说必须要加上synchronized关键字保证同步
[解决办法]
帮顶