一个初级线程的问题,望高手解决一下-_#
一般来说对于下面的这段代码:
class TicketSystem
{
public static void main(String[] args)
{
SellTicket st = new SellTicket();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellTicket implements Runnable
{
int tickets = 100;
public void run()
{
while(true)
{
if(tickets > 0)
{
System.out.println(Thread.currentThread().getName() + " sell ticket: " + tickets);
tickets--;
}
}
}
}
出来的结果应该是:
Thread-0 sell ticket: 100
Thread-0 sell ticket: 99
Thread-3 sell ticket: 98
...
Thread-1 sell ticket: 1
但是我这里出来的结果却是:
Thread-0 sell ticket: 10
Thread-0 sell ticket: 99
Thread-3 sell ticket: 99
Thread-3 sell ticket: 98
Thread-2 sell ticket: 99
Thread-2 sell ticket: 96
Thread-2 sell ticket: 95
...
Thread-1 sell ticket: 7
Thread-3 sell ticket: 8
Thread-0 sell ticket: 5
Thread-0 sell ticket: 4
Thread-0 sell ticket: 3
Thread-2 sell ticket: 6
Thread-1 sell ticket: 1
Thread-3 sell ticket: 2
看孙鑫老师的教程没问题。人家的代码和我的一样,可是我的这个结果。。。
迷茫了半天了,请各位帮个忙吧。谢谢了!
对了,我这里用的是SUN公司的JDK 1.6.0_02。
------解决方案--------------------class TicketSystem {
public static void main(String[] args) {
SellTicket st = new SellTicket();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellTicket implements Runnable {
int tickets = 100;
public synchronized void run() {
while (true) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()
+ " sell ticket: " + tickets);
tickets--;
}
}
}
}