【发布时间】:2020-02-02 10:43:32
【问题描述】:
以下是代码 - AtomicInteger
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorExample1 {
public static void main(String[] args) {
ExecutorService executorService= Executors.newFixedThreadPool(2);
executorService.execute(new MyTask());
executorService.execute(new MyTask());
executorService.execute(new MyTask());
executorService.shutdown();
}
}
class MyTask implements Runnable{
private static AtomicInteger count = new AtomicInteger(0);
@Override
public void run() {
try {
count.addAndGet(1);
task();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void task()throws InterruptedException{
System.out.println(count + " Enterd Run of: " + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(count + " Executing: " + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(count + " Completed Executing: " + Thread.currentThread().getName());
}
}
以上代码输出:
2 进入运行:pool-1-thread-1 2 进入运行:pool-1-thread-2 2 执行:pool-1-thread-2 2 执行:pool-1-thread-1 2 完成执行:pool-1-thread-1 2 完成执行:pool-1-thread-2 3 进入运行:pool-1-thread-1 3 执行:pool-1-thread-1 3 完成执行:pool-1-thread-1用 int 和同步块替换 AtomicInteger 的相同代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorExample1 {
public static void main(String[] args) {
ExecutorService executorService= Executors.newFixedThreadPool(2);
executorService.execute(new MyTask());
executorService.execute(new MyTask());
executorService.execute(new MyTask());
executorService.shutdown();
}
}
class MyTask implements Runnable{
//private static AtomicInteger count = new AtomicInteger(0);
private static int count = 0;
@Override
public void run() {
try {
//count.addAndGet(1);
synchronized (MyTask.class){
count+=1;
}
task();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void task()throws InterruptedException{
System.out.println(count + " Enterd Run of: " + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(count + " Executing: " + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(count + " Completed Executing: " + Thread.currentThread().getName());
}
}
同步块代码的输出
2 进入运行:pool-1-thread-2 1 进入运行:pool-1-thread-1 2 执行:pool-1-thread-2 2 执行:pool-1-thread-1 2 完成执行:pool-1-thread-2 2 完成执行:pool-1-thread-1 3 进入运行:pool-1-thread-2 3 执行:pool-1-thread-2 3 完成执行:pool-1-thread-2问题?
- 为什么输出会有差异?
- 为什么原子整数会增加到 2 而不是 1。
- 如何使用 atomicinteger 实现同步输出。
- 同时使用 volatile 和 atomic 有什么好处或用途?
【问题讨论】:
-
期望是count维护线程执行run方法的计数。
-
顺便说一句,在您的第二个示例中,您在同步块中增加变量,但是当您读取它时,您不会同步,这可能会产生可见性问题。
标签: java multithreading concurrency executorservice compare-and-swap