public class Demo_Thread{
public static void main(String [] args){
Demo_Ticket ticket= new Demo_Ticket();
//开启线程
Thread t1 = new Thread(ticket);
Thread t1 = new Thread(ticket);
Thread t1 = new Thread(ticket);
//线程开启
t1.start();
t2.start();
t3.start();
}
}
public class Demo_02Ticket implements Runnable{
//成员位置,定义100张票
private int tickets = 100;
//Lock lock = new ReentrantLock();
private Object obj = new Object();
public void run(){
while(true){
//同步代码块
synchronized(obj){
//进行售票操作,减法
if(tickets>0){
try{
Thread.sleep(10);
}catch(Exception ex)
{
}
System.out.println(Thread.currentThread().getName()+" 出售第 "+tickets--);
}
}
}
}
}
|
|