新手请教一个多线程中同步的问题
- Java code
class Demo implements Runnable{ private int ticket = 10 ; public synchronized void fun() { if (this.ticket >0) { try { Thread.sleep(100); } catch (Exception e) { } System.out.println(Thread.currentThread().getName()+"-->卖票:"+this.ticket--); } } public void run() { while(ticket>0) { this.fun(); } }}public class ThreadDemo07{ public static void main(String[] args) { Demo d = new Demo(); Thread t1 = new Thread(d,"A"); Thread t2 = new Thread(d,"B"); Thread t3 = new Thread(d,"C"); t1.start(); t2.start(); t3.start(); }}我这个程序是照着视频写的.
为什么我执行出来的结果跟视频中的不一样呢?
我执行出来的全部是A...
[解决办法]
对的,代码没问题的,你不妨将sleep值设大点