Why is synchronized not working properly?

前端 未结 5 588
渐次进展
渐次进展 2020-12-11 06:55

Here\'s my code:

private int count = 0;

  public synchronized void increment() {
      count++;
  }

 public void doWork() throws InterruptedException {

          


        
5条回答
  •  死守一世寂寞
    2020-12-11 07:33

    One alternative solution without using synchronized.

    Since your use case is simple ( just incrimenting the counter and print the value, AtomicInteger is better choice.

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class TestCounter{
        private AtomicInteger count = new AtomicInteger(0);
    
        public void doWork() throws InterruptedException {
    
            Thread t1 = new Thread(new Runnable() {
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(""+Thread.currentThread().getName()+":"+count.incrementAndGet());
                    }}});
    
            Thread t2 = new Thread(new Runnable() {
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(""+Thread.currentThread().getName()+":"+count.incrementAndGet());
                    }}});
    
            t1.start();
            t2.start();
        }
    
        public static void main(String args[]) throws Exception{
            TestCounter tc = new TestCounter();
            tc.doWork();
        }
    }
    

    output:

    Thread-0:1
    Thread-0:3
    Thread-0:4
    Thread-0:5
    Thread-0:6
    Thread-1:2
    Thread-1:7
    Thread-1:8
    Thread-1:9
    Thread-1:10
    

    Refer to @fabian answer for why these numbers are nor not printed in sequence.

    If you expect the sequence in series of numbers in ascending order from 1-10, Threads are not required.

提交回复
热议问题