当前位置:编程学习 > JAVA >>

多线程如何最小化的同步?

写了个类来测试如何最少化的同步,我发现如果在public void run() {}在 加上synchronized 这是正确的结果,但是我感觉这个同步的代码块过大,想学习下如何最小化的对代码同步达到同样的效果,请高手们给指点下,多谢。

public class ThreadTest {

public static void main(String[] args) throws Exception {

ExecutorService executorService = Executors.newFixedThreadPool(10);
Thread11 threade1 = new Thread11();
for (int i = 1; i < 10; i++) {
executorService.execute(threade1);
}
}

static class Thread11 extends Thread {
private Integer threadNo = 0;

private int num = 0;

public synchronized int getNo() {
return num;
}

public synchronized void add() {
this.num = num + 1;
}

public synchronized void mius() {
this.num = num - 1;
}
public void run() {
synchronized (threadNo) {
threadNo++;
}
System.out.println("No." + threadNo + " value:" + getNo());
add();
System.out.println("No." + threadNo + " add value:" + getNo());
mius();
System.out.println("No." + threadNo + " mius value:" + getNo());

}
}
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,