synchronized对线程顺序和出现次数的影响

来源:百度知道 编辑:UC知道 时间:2024/06/01 16:41:37
class TicketsSystem
{
public static void 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)
{
synchronized(obj)
{

if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}

}

}
}

}
这个程序运行结果是thread 1 sell tickets:100
thread 2 sell tickets:100
thread 3 sell tickets:100
thread 4 sell tickets:100
thread 1 sell tickets:100
thread 2 sell tickets:100
thread 3 sell tickets:100
thread 4 sell tickets:100
奇怪的是线程的选择应该

不明白你synchronized(obj) 这里为什么synchronized里的参数会是obj,这个obj对应的是哪个对象?这样写程序应该是有错误的吧。

我跑了一下你的程序(*部分修改了一点)

public class TicketsSystem{

/**
* 主な処理
* @param args
*/
public static void 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)
{
synchronized(new SellThread())//*必须保证同一个synchronized对象才能保证不出问题。
{

if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
}

}
}

}

结果是:
Thread-0 sell tickets:100
Thread-0 sell tick