本帖最后由 橸瑩膤漃寞林 于 2014-4-15 13:54 编辑
public class ThisLockDemo {
public static void main(String[] args) {
Ticket2 t = new Ticket2();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
t.flag = false;
t2.start();
}
}
class Ticket2 implements Runnable{
private int tick = 100;
boolean flag = true;
public void run() {
if (flag) {
//为什么用while,为什么括号里是true ,而不能写false
while(true){
synchronized (this) {
if (tick>0) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()+"......code...."+tick--);
}
}
}
}
else
while(true)//为什么用while
show();
}
public synchronized void show(){
if (tick>0) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()+"......show...."+tick--);
}
}
}
|