无意发现,synchronized(对象) {...},中的对象貌似不可以使用匿名对象.如果使用匿名对象,貌似起不到锁的效果。大神指教??
PS:如果我把代码放在帖子的代码<>里面,根本显示不出,层次括号。我还是直接放在文档中了吧。
<code>
class Ticket implements Runnable{ Object obj = new Object(); private int tick = 1050; /* //-ok --1 Ticket(int tick) { this.tick = tick; } */ public void run()// throws InterruptedException { while(true) { synchronized(new Object())//--这里如果使用匿名对象,起不到监视作用 { if(tick>0) { try { Thread.sleep(10);} catch (Exception e) {} System.out.print(Thread.currentThread().getName()+".."+ tick--+" "); //throw new InterruptedException(); //--error-只能catch,不能throw。因为父类run没有throws } } } }}class ThreadSafeDemo{ public static void main(String[] args) { //Ticket t = new Ticket(100); //-ok --1 Ticket t = new Ticket(); Thread th1 = new Thread(t); Thread th2 = new Thread(t); Thread th3 = new Thread(t); th1.start(); th2.start(); th3.start(); }}</code>运行结果如下(最有一小段):Thread-2..2
Thread-1..1
Thread-0..0
Thread-2..-1。———————————————————————————————————————————— 不多说,这个结果大家也看到了。so,what is the reason ? who can help me??? file:///C:/Users/ADMINI~1/AppData/Local/Temp/SGTpbq/1620/00809906.gif
|
-
1.jpg
(76.9 KB, 下载次数: 18)
运行结果
|