Java 怎么让线程共享counter

2019年7月21日10:49:45 评论 66

1.简介

Java 怎么让线程共享counter?——请看下文。

2.代码

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


public class SharedCounter {
    private static int counter = 0;

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

    Thread thread1 = new Thread(() -> sharedCounter1.increment());
    thread1.start();
    Thread thread2 = new Thread(() -> sharedCounter2.increment());
    thread2.start();

    thread1.join();
    thread2.join();

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

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

 

3.总结

示例代码演示了 Java 怎么让线程共享counter,具体步骤参见示例代码。

发表评论

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