Java Multithreading - Threadsafe Counter

前端 未结 4 2052
借酒劲吻你
借酒劲吻你 2020-12-28 08:27

I\'m starting off with a very simple example in multithreading. I\'m trying to make a threadsafe counter. I want to create two threads that increment the counter intermitten

4条回答
  •  眼角桃花
    2020-12-28 09:05

    You could use the AtomicInteger. It is a class that can be incremented atomically, so two seperate threads calling its increment method do not interleave.

    public class ThreadsExample implements Runnable {
         static AtomicInteger counter = new AtomicInteger(1); // a global counter
    
         public ThreadsExample() {
         }
    
         static void incrementCounter() {
              System.out.println(Thread.currentThread().getName() + ": " + counter.getAndIncrement());
         }
    
         @Override
         public void run() {
              while(counter.get() < 1000){
                   incrementCounter();
              }
         }
    
         public static void main(String[] args) {
              ThreadsExample te = new ThreadsExample();
              Thread thread1 = new Thread(te);
              Thread thread2 = new Thread(te);
    
              thread1.start();
              thread2.start();          
         }
    }
    

提交回复
热议问题