A small Java thread example (like train ticket sales), java thread
Public class MyThread extends Thread {private static int ticket = 100; public void run () {for (int I = 0; I <50; I ++) if (ticket> 0) system. out. println (Thread. currentThread (). getName () + "selling" + (ticket --) + "tickets");} // The main function is a main thread public static void main (String [] args) {MyThread mt = new MyThread (); Thread m1 = new Thread (mt, "window1"); Thread m2 = new Thread (mt, "window2 "); thread m3 = new Thread (mt, "window3"); m1.start (); m2.start (); m3.start ();}}
Similar to the sales of train tickets, different windows sell the same ticket. Two windows cannot sell the same ticket.
JAVA five windows sell 100 train tickets with multiple threads
Well, you can write one for you. Each ticket sales window is 0 ~ Sell a ticket within 5 seconds
Package thread. baidu;
Import java. util. ArrayList;
Import java. util. List;
Import java. util. Random;
Import java. util. concurrent. TimeUnit;
/**
* Use list as container
* There are no producers, because there are so many tickets.
* Solder is a consumer
* @ Version SoldTicket. java v. 1.0.0 2010-11-10
* @ Author Andy
*/
Public class SoldTicket {
Public static List <String> list = new ArrayList <String> ();
Public static int counter = 1;
Public static Random random = new Random ();
Public static void main (String [] args ){
InitTickets ();
SoldTicket st = new SoldTicket ();
For (int I = 1; I <= 5; I ++ ){
St. new Solder (). start ();
}
}
Private synchronized String getOneTicket (){
If (list. size () <= 0) return null;
Return list. remove (0 );
}
Private static void initTickets (){
For (int I = 1; I <= 100; I ++ ){
List. add ("no." + I + "tickets ");
}
}
/**
* Ticket sales
* @ Version SoldTicket. java v. 1.0.0 2010-11-10
* @ Author Andy
* Copyright (c) 2010 Beijing sanghawu Network Technology Co., Ltd. www.3jia5.com
*/
Class Solder extends Thread {
Public final int id = counter ++;
Public Solder (){
This. setName ("ticket window" + id );
}
@ Override
Public void run (){
While (! This. isInterrupted ()){
String ticket = getOneTicket ();
If (ticket = null ){
System. out. println (this. getName () + ": the ticket has been sold empty. Please wait ");
Break;
}
System. out. println (this. getName () + "sold" + tic ...... the remaining full text>
A multi-threaded java program
Query Information
Li has many similar examples.