/*
把同步加在while循环内和加在循环外有什么区别呢?
为什么一个会运行多个线程
一个却在打印的时候只运行一个线程呢。求解
*/
class Test1 implements Runnable {
Object obj = new Object();
private int piao = 100;
public void run() {
while(true) {
synchronized(obj) {
if(piao > 0) {
try {Thread.sleep(10);} catch(InterruptedException e) {}
System.out.println("show run..." + piao--);
}
}
}
}
}
class Test2 implements Runnable {
Object obj = new Object();
private int piao = 100;
public void run() {
synchronized(obj) {
while(true) {
if(piao > 0) {
try {Thread.sleep(10);} catch(InterruptedException e) {}
System.out.println("show run..." + piao--);
}
}
}
}
} |
|