62,634
社区成员




package Lesson8;
class SellThread extends Thread {
private Tickets tickets;
public SellThread(Tickets tickets)
{
this.tickets=tickets;
}
public void run() {
while (tickets.getNum()>0) {
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickets.sell();
}
}
}
public class Demo3 {
public static void main(String args[]) {
Tickets tickets=new Tickets(20);
SellThread st1 = new SellThread(tickets);
SellThread st2 = new SellThread(tickets);
SellThread st3 = new SellThread(tickets);
SellThread st4 = new SellThread(tickets);
st1.start();
st2.start();
st3.start();
st4.start();
}
}
class Tickets
{
private int num=0;
public int getNum()
{
return num;
}
public Tickets(int num)
{
this.num=num;
}
public synchronized void sell()// 线程同步方法
{
if (num > 0) {
System.out.println(Thread.currentThread().getName()
+ " sell tickets:" + num);
num--;
}
}
}