Runnable卖票
publicclass Main {
publicstaticvoid main(String[] args) {
//测试RunnableMyThread1 t1 =new MyThread1();
newThread(t1).start();//同一个t1,如果在Thread中就不行,会报错new Thread(t1).start();
new Thread(t1).start();
}
}classMyThread1implements Runnable{
privateintticket = 10;
@Override
//记得要资源公共,要在run方法之前加上synchronized关键字,要不然会出现抢资源的情况publicsynchronizedvoid run() {
for(inti = 0; i <10; i++) {
if(this.ticket>0) {
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
}
Thread卖票
publicclassMyThreadTestextends Thread {
privateintticket=20;
publicvoid run() {
while(true) {
synchronized(this) {
Thread.sleep(100);
if(ticket>0) {
System.out.println(Thread.currentThread().getName() + "..." + ticket--);
} else {
break;
}
}
}
}
publicstaticvoid main(String[] args) {
Thread t1 =newThread(myThreadTest1, "窗口1");
Thread t2 =newThread(myThreadTest1, "窗口2");
t1.start();
t2.start();
}
}