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

2019年7月21日10:50:53 评论 931字阅读3分6秒

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++;
            }
        }
    }
}

 
展开全文
  • 版权所有:编程十万个怎么办
  • 转载注明:https://www.tah1986.com/27361.html
匿名

发表评论

匿名网友 填写信息

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