Java学习中,目前在看多线程
所调试的例题是经典的多点售票程序
为了防止售票点因为资源不同步的原因,而卖出超过实际票数的票
则使用了synchronized关键字
结果的确不会再卖出-1票了
但是调试结果貌似不太理想,如果票数少,就基本上是第一个售票点卖完了
即便票数多(100张),线程也不是交替运行,而是一时全A,一时全B
请帮忙查看代码是否有错,逻辑是否合理
谢谢!
代码:
class Test24_04 implements Runnable{
private int piao = 10;
public void run(){
while(this.piao > 0){
this.fun();
}
}
public synchronized void fun(){
if(this.piao > 0){
try{
Thread.sleep(100);
}catch(Exception e){
;
}
System.out.println(Thread.currentThread().getName() + " 卖票了,剩余票数:" + (this.piao--));
}
}
}
public class JavaTest24_04{
public static void main(String args[]){
Test24_04 t = new Test24_04();
Thread t1 = new Thread(t,"售票点A");
Thread t2 = new Thread(t,"售票点B");
Thread t3 = new Thread(t,"售票点C");
t1.start();
t2.start();
t3.start();
}
}
//使用synchroized关键字实现线程对资源的同步操作
看起来是涉及到java内部底层实现. 似乎thread刚释放monitor锁之后立刻去再申请, 得到monitor的机会更大一些.
把sleep()放在run()里 就避免了这样的问题, 可以得到想要的结果.