关于多线程的执行顺序(初学)
犹豫再三,还是决定提问,这两天线程的执行顺序搞的我好晕!!
class Q {
int n;
boolean valueSet=true;
synchronized void put(int n) {
if(!valueSet)
try{
wait();
}catch(InterruptedException e){
System.out.println("Interrupted exception caught.");
}
this.n = n;
System.out.println("Put: " + n);
valueSet=false;
notify();
}
synchronized int get() {
if(valueSet)
try{
wait();
}catch(InterruptedException e){
System.out.println("Interrupted exception caught.");
}
System.out.println("Got: " + n);
valueSet=true;
notify();
return n;
}
}
//======================================================
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
// while(true) {
for(int m=15;m>0;m--)
q.put(i++);
// }
}
}
//======================================================
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
// while(true) {
for(int m=15;m>0;m--)
q.get();
// }
}
}
//======================================================
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
//======================================================
在单位电脑的赛洋单核CPU上执行结果:
Press Control-C to stop.
Put: 0
Got: 0
Put: 1
Got: 1
... ...
在家里的AMD双核4000+上的执行结果:
Put: 0
Press Control-C to stop.
Got: 0
Put: 1
Got: 1
... ...
其实这个main的println语句什么时候执行我还是不明白。
println在main方法的最后,据我的理解应该在所有子线程结束之后执行,或在子线程互斥的间隙执行。
main的println为什么会最先执行呢?
子线程的互斥应该没有间隙啊,为什么main的println出线在Put: 0与Got: 0中间呢?
难道主线程和所有子线程的执行顺序都是随机的?