class Ticket implements Runnable{
private int tick = 1000;
public synchronized void run() {
while(true){
if(tick>0){
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()+"...sale"+tick--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class ThisLockDemo {
public static void main(String[] args){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
输出结果:
Thread-0...sale1000
Thread-0...sale999
Thread-0...sale998
Thread-0...sale997
Thread-0...sale996
Thread-0...sale995
Thread-0...sale994
....
这个程序怎么老是一个线程在执行?为什么会这样?
--------------------------------------------------------------------
class Ticket2 implements Runnable{
private int tick = 1000;
public void run() {
while(true){
show();
}
}
public synchronized void show(){
if(tick>0){
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()+"...sale"+tick--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThisLockDemo2 {
public static void main(String[] args){
Ticket2 t = new Ticket2();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
输出结果:
....
Thread-0...sale988
Thread-0...sale987
Thread-0...sale986
Thread-0...sale985
Thread-3...sale984
Thread-3...sale983
Thread-3...sale982
Thread-3...sale981
Thread-3...sale980
....
这个程序我感觉和上面程序差不多啊。为什么这个程序是4个线程交替执行的?和上面程序有什么差别? |