如何在 java 中实现除 atomicInteger 之外的线程安全

How to implement thread safety aside from atomicInteger in java

目前我是 Java 并发的新手。我很难找到另一种方法 在不将计数器设置为 atomicInteger 的情况下线程安全的 process 方法?如果我尝试将同步放在进程方法上,它将消除并发的概念。

感谢您的帮助,谢谢!

public class SingleThread {
      private static int counter;

      public static void process() throws InterruptedException {

        for (int i = 0; i < 1000; i++) {
          counter++;
          Thread.sleep(1);
        }

      }



      public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        // START of workable area
        int numThreads = 5;


        List < Thread > threads = new ArrayList();

        for (int i = 0; i < numThreads; i++) {
          var thread = new Thread(new Runnable() {

            @Override
            public void run() {
              try {
                process();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }

            }
          });

          thread.start();
          threads.add(thread);

        }

        for (Thread thread: threads) {
          thread.join();
        }

        // END of workable area
        long end = System.currentTimeMillis();

        System.out.println("Time: " + (end - start) + " ms");
        System.out.println("Data Count: " + counter);
      }


    }

使用 synchronized 块,而不是将其放在整个方法中。

public static void process() throws InterruptedException {

  for (int i = 0; i < 1000; i++) {
    synchronized (SingleThread.class) {
      counter++;
    }
    Thread.sleep(1);
  }

}