class Sale
{
public static void main(String [] args)
{
Runnable r = new SaleTickets();
Thread t1 = new Thread(r);
t1.start();
Thread t2 = new Thread(r);
t2.start();
Thread t3 = new Thread(r);
t3.start();
Thread t4 = new Thread(r);
t4.start();
}
}
第二个程序实现了同步:
class SaleTickets implements Runnable
{
int tickets = 100;
String str = new String("");
public void run()
{
while(true)
{
synchronized(str)
{
if(tickets>0)
{ try
{
Thread.sleep(10);
}
catch(Exception e)
{
class Sale
{
public static void main(String [] args)
{
Runnable r = new SaleTickets();
Thread t1 = new Thread(r);
t1.start();
Thread t2 = new Thread(r);
t2.start();
Thread t3 = new Thread(r);
t3.start();
Thread t4 = new Thread(r);
t4.start();
}