Java – why count less or even use the synchronized keyword?

I began to learn some Java concurrency concepts

public class Count { 
    private int count = 0; 
    public synchronized void setCount(int count) { 
        this.count = count; 
    } 
    public synchronized int getCount() { 
        return count; 
    } 
} 
class CountRunner extends Thread { 
    Count count; 
    public CountRunner(Count count) { 
        this.count = count; 
    } 
    public void run() { 
        for (int i = 1; i <= 1000; i++) { 
            count.setCount(count.getCount() + 1); 
        } 
    } 
} 
class TestCount { 
    public static void main(String[] args) throws Exception { 
        Count count = new Count(); 
        CountRunner runnerA = new CountRunner(count); 
        CountRunner runnerB = new CountRunner(count); 
        runnerA.start(); 
        runnerB.start();         
        runnerA.join(); //join statement here 
        runnerB.join(); 
        System.out.println("count.getCount = " + count.getCount()); 
    } 
}
Question:
1. The result is a little less than 2000 for many times,why ?
2. if delete 2 join() statement,why count.getCount = 451,even less ?
3. i think there will be no effect of deleting the join() statements,because i already have Synchronized method to lock one object to one thread each time ? 
So,What's the point of using Synchronized and join() ?

Solution

It's simple Call setcount method 1 by calling getcount Before entering the method, the runtime will calculate getcount (synchronized), but you will not keep locked when leaving getcount and entering setcount and other threads can call getcount Therefore, every two (or more, depending on the number of threads you create) threads will have the same value in getcount Imagine that thread a enters and receives the value 1. 0 in getcount The runtime generates that it executes to tread B, which calls getcount and receives the same value 1 Thread B sets the value to 1 and runs 50 times again, so your count will be 50 at this stage The runtime generates and executes to thread a, and thread a calls setcount to 1 (remember that it doesn't try to call setcount and generate its exec) Now a sets the value to 1 (this is wrong)

Change the implementation you run:

public void run() { 
    for (int i = 1; i <= 1000; i++) {
      synchronized(count){ 
        count.setCount(count.getCount() + 1); 
      }
    } 
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>