Using java multi-threaded simulation of train tickets. . . .

 

public class Demo01 {

public static void main(String[] args) {
// TODO Auto-generated method stub
//Problems that will occur when multiple threads are parallel
//Synchronization:
//Buy train tickets, four windows A, B, C, D

//Create a task
TicketTask task = new TicketTask();

//Four windows A,B,C,D
new Thread(task).start();
new Thread(task).start();
new Thread(task). start();
new Thread(task).start();
}

}

//The task of buying tickets
class TicketTask implements Runnable{

//assume there are only 100 tickets
private static int ticket = 100;

//synchronized method
@Override
public synchronized void run() {
while(true){
if(ticket <= 0){
System.out.println("The train ticket has been Sold out...");
break;
}else{
System.out.println("Congratulations on buying a train ticket: seat number:" + ticket);
ticket--;
}
}
}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324976813&siteId=291194637