Java 怎么实现5个线程每增加一个共享int计数器1000次

2019年7月21日10:50:53 评论 61

1.简介

Java 怎么实现5个线程每增加一个共享int计数器1000次?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

public class Main {
    private int counter = 0;

    public static void main(String[] args) throws InterruptedException {
    long startTime = System.currentTimeMillis();
    Main sharedCounter1 = new Main();

    Thread thread1 = new Thread(() -> sharedCounter1.increment());
    thread1.start();
    Thread thread2 = new Thread(() -> sharedCounter1.increment());
    thread2.start();
    Thread thread3 = new Thread(() -> sharedCounter1.increment());
    thread3.start();
    Thread thread4 = new Thread(() -> sharedCounter1.increment());
    thread4.start();
    Thread thread5 = new Thread(() -> sharedCounter1.increment());
    thread5.start();

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();
    thread5.join();

    long endTime = System.currentTimeMillis();
    System.out.println("Counter: " + sharedCounter1.counter);
    System.out.println("Total time taken(in millis): " + (endTime - startTime));
}

    public void increment() {
        for (int i = 0; i < 1000; i++) {
            synchronized (Main.class) {
                
                counter++;
            }
        }
    }
}

 

3.总结

示例代码演示了 Java 怎么实现5个线程每增加一个共享int计数器1000次,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: