synchronized

来源:互联网 发布:盘锦中小企业seo 编辑:程序博客网 时间:2024/06/17 17:42


synchronized下面两种写法是等效的 推荐使用t2 尽量锁住最小的同步单位


synchronized void t(){}void t2(){synchronized(this){}}

这两种也是等效的

static synchronized void t(){}static void t1(){synchronized(Run1.class){}}




例1:

public class Sync {static int num=0;public static void main(String[] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool();executorService.execute(new Run1());executorService.execute(new Run1());executorService.execute(new Run1());executorService.execute(new Run1());Thread.sleep(100);System.out.println(num);}static class Run1 implements Runnable{@Overridepublic void run() {t();}void t(){for(int i=0;i<100000;i++){synchronized(this){num++;}}}}}

输出随机 小于40w

因为 线程执行的是不同的对象 所以互补干扰

修改代码 

将 synchronized(this) 改为 synchronized(this.getClass())

这样输出 就为40w  

或者 将线程池去执行同一个Runnable实例 这样 执行结果也是40w

Run1 r  = new Run1();executorService.execute(r);executorService.execute(r);executorService.execute(r);executorService.execute(r);















原创粉丝点击