输出:
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"
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"
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关键字保证同步