凯
package ticket; class Tickets { public static void main(String[] args) { sellTickets st = new sellTickets(); //四个线程同时卖这100张票,注意是同一个对象创建四个线程,他们共享同一个变量ticket new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); } } class sellTickets implements Runnable { int ticket = 100; Object o = new Object(); @Override public void run() { while(true) { //每一个对象都有一个监视器,或者叫做锁。同步块示例 synchronized (o) { if(ticket > 0) { //存在的隐藏的问题当ticket=1,它的时间片到期了进入到if语句中,第二个线程进入到if语句然后时间片到期 try { //线程睡眠,该方法需要写异常 Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //第几个线程卖出了第多少张票 System.out.println(Thread.currentThread().getName() + "sell tickets" + ticket); ticket--; } } } } }
public class Singleton5 {
private static Singleton5 instance;
private Singleton5(){
}
public static Singleton5 getInstance(){
if(instance == null){
synchronized (Singleton5.class) {
if(instance == null){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new Singleton5();
}
}
}
return instance;
}
} ublic class com.bigdata.juc.singleton.Singleton5 {
public static com.bigdata.juc.singleton.Singleton5 getInstance();
Code:
0: getstatic #2 // Field instance:Lcom/bigdata/juc/singleton/Singleton5;
3: ifnonnull 51
6: ldc #3 // class com/bigdata/juc/singleton/Singleton5
8: dup
9: astore_0
//反编译后加上了 monitorenter和monitorexit
10: monitorenter
11: getstatic #2 // Field instance:Lcom/bigdata/juc/singleton/Singleton5;
14: ifnonnull 41
17: ldc2_w #4 // long 1000l
20: invokestatic #6 // Method java/lang/Thread.sleep:(J)V
23: goto 31
26: astore_1
27: aload_1
28: invokevirtual #8 // Method java/lang/InterruptedException.printStackTrace:()V
31: new #3 // class com/bigdata/juc/singleton/Singleton5
34: dup
35: invokespecial #9 // Method "<init>":()V
38: putstatic #2 // Field instance:Lcom/bigdata/juc/singleton/Singleton5;
41: aload_0
//和monitorenter成对出现
42: monitorexit
43: goto 51
46: astore_2
47: aload_0
//这个monitorexit防止无法正常释放锁的
48: monitorexit
49: aload_2
50: athrow
51: getstatic #2 // Field instance:Lcom/bigdata/juc/singleton/Singleton5;
54: areturn