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);
}
}
}
这个程序的问题是
一,常常会出现一个站点大量出票,而另一个站点一个票也没有出,怎么回事?怎样改进?
二,在统计各个站点的票数时会出现三行,如下所示:

怎样解决,就出现一行,统计各个站点的票数。
------解决方案--------------------
1.没办法改进,cpu的问题,把票数改大点就自然了
2.其实A不需要三个成员变量,一个就够了
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++;
}