package javathread;
public class ticketsell implements Runnable{
private volatile int tickets=30;
Object lock =new Object();
@Override
public void run() {
while(tickets>0){
synchronized (lock){
System.out.println(Thread.currentThread().getName() + "终于卖了第" + tickets + "张票/n");
tickets--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
package javathread;
public class testticketsell {
public static void main(String[] args) {
ticketsell t=new ticketsell();
Thread t1=new Thread(t,"t1");
Thread t2=new Thread(t,"t2");
Thread t3=new Thread(t,"t3");
t2.start();
t1.start();
t3.start();
}
}
运行结果:
1.为什么会出现0和-1呢?我觉得应该与while的判断条件在synchronized代码块外有关,可以解释下底层原因吗?
2.每次运行结果都是如此,不应该是随机出现吗?怎么前面一直是线程2抢到?