本帖最后由 821728010 于 2013-5-29 17:36 编辑
刚刚看了多线程,试着写了下代码,为什么只有一个线程在卖票?我都搞到100张票了,其他线程还抢不到么?
import java.lang.*;
import org.omg.CORBA.Current;
public class Demo2 {
public static void main(String[] args) {
Tiket ti = new Tiket();
Thread th1 = new Thread(ti);
Thread th2 = new Thread(ti);
Thread th3 = new Thread(ti);
Thread th4 = new Thread(ti);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class Tiket implements Runnable{
int ticket = 100;
public void run(){
synchronized (this) {
while(true){
synchronized (this) {
if(ticket>0){
System.out.println(Thread.currentThread()+"第"+ticket+"张票");
ticket--;
}else{
break;
}
}
}
}
}
} |