62,625
社区成员
发帖
与我相关
我的任务
分享
import java.util.Date;
public class Test{
public static void main(String[] args){
Ticket ticket = new Ticket(50);
Window[] windows = new Window[6];
long start = new Date().getTime();
for(int i = 0 ; i < windows.length ; i ++){
windows[i] = new Window("Window-" + (i + 1),ticket);
}
for(int i = 0 ; i < windows.length ; i ++){
windows[i].start();
}
for(int i = 0 ; i < windows.length ; i ++){
try{
windows[i].join();
}catch(InterruptedException e){
e.printStackTrace();
return;
}
}
long end = new Date().getTime();
System.out.printf("%nTotal cost:%.3f seconds.%n",(end - start) / 1000.0);
}
}
class Window extends Thread{
public Window(String name,Ticket ticket){
super(name);
this.ticket = ticket;
}
public void run(){
while(ticket.hasRemaining()){
ticket.sellTicket();
System.out.printf("%s:sell one ticket.%n",Thread.currentThread().getName());
try{
Thread.sleep(1000);//1秒钟时间出票
}catch(InterruptedException e){
e.printStackTrace();
return;
}
}
}
private Ticket ticket;
}
class Ticket{
public Ticket(int ticketLeft){
this.ticketLeft = ticketLeft;
}
public synchronized void sellTicket(){
ticketLeft --;
}
public boolean hasRemaining(){
return ticketLeft > 0;
}
private int ticketLeft;
}
