Second article content
Class Ticket implements Runnable//extends thread//implementation Runnable interface
{
public int tic = 100;
Object obj = new Object ();
public void Run ()
{
while (TRUE)//default is True
{
Synchronized (obj)//Synchronous code block
{
if (tic>0)
{//If the number of votes is greater than 0 execute the following code.
Try
{Thread.Sleep (10);}
catch (Exception e)
{
}
System.out.println (Thread.CurrentThread (). GetName () + "sole ..." +tic--);//define the thread name and reduce the number of votes.
}
}
}
}
}
Class Ticketdemo
{
public static void Main (string[] args)
{
Ticket t = new Ticket ();//define Ticket object.
thread T1 = new Thread (t); The subclass object of the Runnable interface is passed into the constructor of the thread class as an actual parameter.
Thread t2 = new Thread (t);
thread t3 = new Thread (t);
Thread t4= new Thread (t);
T1.start ();
T2.start ();
T3.start ();
T4.start ();
Start 4 threads.
}
}
Complete the small program!
This article is from the "Flying Scorpion" blog, please be sure to keep this source http://tanglongwei.blog.51cto.com/4411684/1671585
Sell ticket Applet (ii): Solve thread security hidden trouble!