多线程卖票

来源:互联网 发布:睿至大数据孙亮 编辑:程序博客网 时间:2024/05/17 02:24

public class Demo {
public static void main(String[] args) {
MyRunable my1 = new MyRunable();
Thread th1 = new Thread(my1);
Thread th2 = new Thread(my1);
Thread th3 = new Thread(my1);
th1.start();
th2.start();
th3.start();
}

}






public class MyRunable implements Runnable{
/*int a =100;
Object lock = new Object();
public void run() {
while(a>0){
synchronized (lock) {
if(a>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+(a--));
}
}

}
}*/
int a = 0;
Object o = new Object();

public void run() {
for(int i = a;i<100;i++){
synchronized (o) {
if(a<100){
a++;
System.out.println(Thread.currentThread().getName()+"  "+a);
}
}
}
}
}



0 0
原创粉丝点击