日期:2014-05-20 浏览次数:20678 次
import java.util.*;
public class Test
{
public static void main(String[] args)
{
A aa1 = new A();
aa1.start();
A aa2 = new A();
aa2.start();
A aa3 = new A();
aa3.start();
}
}
class A extends Thread
{
private static int ticket = 100;
static String str = new String("qqq");
private int count_0 = 0;
private int count_1 = 0;
private int count_2 = 0;
public void run()
{
while(true)
{
synchronized(str)
{
if(ticket > 0)
{
Date time = new Date();
System.out.printf("%s is doing, and No.%d is sold at the time of %s.\n",
Thread.currentThread().getName(), ticket, time);
ticket--;
if(Thread.currentThread().getName().equals("Thread-0"))
{
count_0++;
}
else if(Thread.currentThread().getName().equals("Thread-1"))
{
count_1++;
}
else
{
count_2++;
}
}
else
{
break;
}
}
}
if(0 == ticket)
{
System.out.printf("\ncount_0 = %d, count_1 = %d, count_2 = %d.\n",
count_0, count_1, count_2);
}
}
}
package com.thread;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
A aa1 = new A();
aa1.setName("Thread1");
aa1.start();
A aa2 = new A();
aa2.setName("Thread2");
aa2.start();
A aa3 = new A();
aa3.setName("Thread3");
aa3.start();
}
}
class A extends Thread
{
private static int ticket = 1000;
static String str = new String("qqq");
private int count = 0;
public void run()
{
while(true)
{
synchronized(str)
{
if(ticket > 0)
{
Date time = new Date();
//System.out.printf("%s is doing, and No.%d is sold at the time of %s.\n",
// Thread.currentThread().getName(), ticket, time);
ticket--;
count++;
}