孙鑫JAVA多线程视频BUG

来源:百度知道 编辑:UC知道 时间:2024/05/02 19:35:20
class TicketsSystem{
public void static main(String[] args){
SellThread st=new SellThread();
new Thread(st).start;
new Thread(st).start;
new Thread(st).start;
new Thread(st).start;
}
}
class SellThread implements Runnable{
int tickets=100;
public void run(){
while(true)
{
if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+"sell tickets:"+tickets);
tickets--;
}
}
}
}
命令提示符输出如下:
Thread-0sell tickets:100
Thread-0sell tickets:99
Thread-0sell tickets:98
Thread-0sell tickets:97
Thread-0sell tickets:96
Thread-0sell tickets:95
Thread-0sell tickets:94
Thread-0sell tickets:93
Thread-3sell tickets:93
Thread-3sell tickets:92
Thread-3sell tickets:91
Thread-3sell tickets:90
Thread-3sell tickets:89
Thread-3sell tickets:88
Thread-3sell tickets:87
Thread-3sell tickets:86
Thread-2se

这就是线程不同步导致的,加个线程同步就行了,后面的教程应该会说,没就只好你自己去看线程同步的相关内容了 :
改了一下,同步了就不会出现这种情况了:
public class TicketsSystem
{

public TicketsSystem()
{
new SellThread();
}
public static void main(String[] args){
new TicketsSystem();
}

}
class SellThread implements Runnable{
int tickets=100;
public SellThread()
{
try{
new Thread(this).start();
new Thread(this).start();
new Thread(this).start();
new Thread(this).start();
}catch(Exception e)
{
e.printStackTrace();
}
}
private synchronized void sale()
{
if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+"sell tickets:"+tickets);
tickets--;
try
{
Thread.sleep(200);
}catch(Exception e)
{
e.printStackTrace(