小编nep*_*uru的帖子

当在关键部分中显示System.out.println时,多个线程显示例外值

我有以下代码:

public class MyApp {
    public static void main(String[] args) throws InterruptedException {
        SharedResource sharedResource = new SharedResource();

        Runnable first = () -> {
            sharedResource.increment(10000);
        };

        Runnable second = () -> {
            sharedResource.increment(10000);
        };

        Thread thread = new Thread(first, "FirstThread");
        Thread thread2 = new Thread(second, "SecondThread");
        thread.start();
        thread2.start();
        thread.join();
        thread2.join();
        System.out.println("The value of counter is " + sharedResource.getCounter());
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这个类:

public class SharedResource {
    private int counter;

    public void increment(int times) {
        for (int x=1; x<=times;x++) {
            counter++;
            // …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading

4
推荐指数
1
解决办法
89
查看次数

标签 统计

concurrency ×1

java ×1

multithreading ×1