Why is synchronized not working properly?

前端 未结 5 593
渐次进展
渐次进展 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:58

    Solution 1: Given by fabian. To give a single function incrementAndGet().

    Solution 2: A synchronized block instead of synchronized method (if possible):

    Complete code would be like:

    private int count = 0;
    private Object dummyObject = new Object();
    
    public void increment() {
        count++;
    }
    
    public int getCount() {
        return count;
    }
    
    public void doWork() throws InterruptedException {
    
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    synchronized (dummyObject) {
                        increment();
                        System.out.println(count + "  " + Thread.currentThread().getName());
                    }
                }
            }
        });
    
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    synchronized (dummyObject) {
                        increment();
                        System.out.println(count + "  " + Thread.currentThread().getName());
                    }
                }
            }
        });
    
        t1.start();
        t2.start();
    }
    

提交回复
热议问题