Java-threadPool - 同步线程
Java-threadPool - synchronize Threds
编辑: 1.) 为什么 "globalCounter" 是同步的,而不是 "Thread.currentThread().getId()"
2.) 我可以为每个线程分配一个计算吗?如何?我可以处理结果吗?
public class Hauptprogramm {
public static final int MAX_THREADS = 10;
public static int globalCounter;
public static Integer syncObject = new Integer(0);
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(MAX_THREADS);
for (int i = 0; i < MAX_THREADS; i++) {
threadPool.submit(new Runnable() {
public void run() {
synchronized (syncObject) {
globalCounter++;
System.out.println(globalCounter);
System.out.println(Thread.currentThread().getId());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}});
}
threadPool.shutdown();
}
}
1.) Why is "globalCounter" synchronized , but not "Thread.currentThread().getId()"
我可以回答为什么 globalCounter
是同步的。避免数据竞争和竞争条件。
万一它不同步 - globalCounter++
计算是一个三步过程(读-修改-写)-
- 读取
globalCounter
变量的当前值。
- 修改其值。
- 将修改后的值写入/赋值回
globalCounter
。
在多线程环境中缺少 synchronization
的情况下,当另一个线程处于这 3 个步骤的过程中时,一个线程可能会读取/修改 globalCounter
的值.
这可能会导致 thread/s 读取陈旧值或丢失更新计数。
2) Can I assign a calculation to each thread? how? Can i work with the results?
这是可能的。您可以查看 Future/ FutureTask 以处理结果
编辑: 1.) 为什么 "globalCounter" 是同步的,而不是 "Thread.currentThread().getId()"
2.) 我可以为每个线程分配一个计算吗?如何?我可以处理结果吗?
public class Hauptprogramm {
public static final int MAX_THREADS = 10;
public static int globalCounter;
public static Integer syncObject = new Integer(0);
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(MAX_THREADS);
for (int i = 0; i < MAX_THREADS; i++) {
threadPool.submit(new Runnable() {
public void run() {
synchronized (syncObject) {
globalCounter++;
System.out.println(globalCounter);
System.out.println(Thread.currentThread().getId());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}});
}
threadPool.shutdown();
}
}
1.) Why is "globalCounter" synchronized , but not "Thread.currentThread().getId()"
我可以回答为什么 globalCounter
是同步的。避免数据竞争和竞争条件。
万一它不同步 - globalCounter++
计算是一个三步过程(读-修改-写)-
- 读取
globalCounter
变量的当前值。 - 修改其值。
- 将修改后的值写入/赋值回
globalCounter
。
在多线程环境中缺少 synchronization
的情况下,当另一个线程处于这 3 个步骤的过程中时,一个线程可能会读取/修改 globalCounter
的值.
这可能会导致 thread/s 读取陈旧值或丢失更新计数。
2) Can I assign a calculation to each thread? how? Can i work with the results?
这是可能的。您可以查看 Future/ FutureTask 以处理结果