class Ticket2 implements Runnable{
private int tick=1;
boolean flag = true;
public void run(){
if(flag){
synchronized(this){
while(tick <= 100){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...code..."+ tick++);
}
}
}
else
show();
}
public synchronized void show(){
while(tick <= 300){
System.out.println(Thread.currentThread().getName()+"...show..."+ tick++);
}
}
}
public class TicketLockDemo {
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 (InterruptedException e) {
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
每次的结果都是先打印Thread-0,1到100,然后就是Thread-1,101到300,为什么不是同步呢,程序有什么问题吗,谁能帮我分析下吗? |
|