两条现成分别运行两个方法,测试同步函数show()是否与run()函数一样,使用的都是Object作为锁。
class Ticket implements Runnable{ PRivate int num = 200; Object obj = new Object(); boolean flag = true; @Override public void run() { if(flag){ while(true){ synchronized (obj) { if(num > 0){ try {Thread.sleep(10);} catch (Exception e) {} //模拟处理时间 System.out.println("run..."+Thread.currentThread().getName()+"...."+num--); } } } }else{ while(true) show(); } } public synchronized void show(){ if(num > 0){ try {Thread.sleep(10);} catch (Exception e) {}//模拟处理时间 System.out.println("show..."+Thread.currentThread().getName()+"..."+num--); } }}public class Test { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try {Thread.sleep(10);} catch (Exception e) {} //减慢速度,不然因为电脑速度过快导致测试不出结果 t.flag = false; t2.start(); }}测试结果
run...Thread-0....1show...Thread-1...1打印的信息中,出现了重复的num,故同步函数的锁并非Object。 查资料知,其锁为this,将synchronized (obj)
改为synchronized (this)
即可验证。
新闻热点
疑难解答