请问通过下面这种方法能起到防止haha()和run()中的synchronized中的内容同时执行的作用吗? public class A{
public synchronized void haha(){
}
class B extends TimerTask{
@Override
public void run(){
synchronized(A.this){
}
}
}
}
1 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
public class A{ int value = 0; final int NUMBER = 1000000; public synchronized void haha(){ for (int i = 0; i < NUMBER; i++) value ++; } class B extends TimerTask{ @Override public void run(){ synchronized(A.this){ for (int i = 0; i < NUMBER; i++) value ++; } } } public static void main(String args[]) throws InterruptedException { A a = new A(); B b = a.new B(); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2); executor.scheduleWithFixedDelay(b, 1, 1, TimeUnit.SECONDS); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { a.haha(); } }, 1, 1, TimeUnit.SECONDS); Thread.sleep(1000 * 9 + 500); executor.shutdownNow(); System.out.printf("value: %d\n", a.value); } }
添加回答
举报
0/150
提交
取消