synchronized
1 package com.cn; 2 3 class Test{ 4 public static void main(String [] args){ 5 TestThread t = new TestThread(); 6 new Thread(t).start(); 7 try { 8 Thread.sleep(10); 9 } catch (InterruptedException e) { 10 e.printStackTrace(); 11 } 12 t.str="method"; 13 new Thread(t).start(); 14 } 15 } 16 17 class TestThread implements Runnable { 18 int tickets = 100; 19 String str = new String(""); 20 public void run() { 21 if(str.equals("method")){ 22 while(true){ 23 synchronized (this) { 24 if(tickets>0){ 25 try { 26 Thread.sleep(10); 27 } catch (InterruptedException e) { 28 e.printStackTrace(); 29 } 30 System.out.println(Thread.currentThread().getName()+" is salling ticket "+tickets--); 31 } 32 } 33 } 34 }else{ 35 while(true){ 36 sale(); 37 } 38 } 39 } 40 public synchronized void sale(){ 41 if(tickets>0){ 42 try { 43 Thread.sleep(10); 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } 47 System.out.println(Thread.currentThread().getName()+" is salling ticket "+tickets--); 48 } 49 } 50 }
sale()方法使用的监视器对象是this,所以要实现同步代码块和sale()方法之间的同步,同步代码块检查的同步对象也应该为this