简体   繁体   中英

I don't know why these outputs come out, (java thread)

output :

Thread1 Start !! 

Thread2 Start !! 

Thread2 End !! 100001

Thread1 End !! 100001

i think output is {1,10001} or {10000,10001} because of sync...

import java.util.*;

public class Main2 {
    public static int shared = 0;
    public synchronized static void sharedIncrease(long amount) {
        while(amount-->0) shared++;
    }
    public static void main(String args[]) throws Exception {
        StrangeThread t1 = new StrangeThread(100000);
        StrangeThread t2 = new StrangeThread(1);
        t1.start();
        t2.start();
    }
}

class StrangeThread extends Thread {
    long amount;
    int thrdNum;
    static int cnt = 1;
    StrangeThread(long value) {
        amount = value;
        thrdNum = cnt++;
    }
    public void run() {
        System.out.println("Thread"+thrdNum+" Start !! ");
        Main2.sharedIncrease(this.amount);
        System.out.println("Thread"+thrdNum+" End !! "+Main2.shared);
    }
}

Consider the following sequence of operations

  1. Thread 1 starts. Prints Thread1 Start !!
  2. Thread 2 starts. Prints Thread2 Start !!
  3. Thread 1 acquires the lock and executes the logic in sharedIncrease (Thread 2 is blocked). When the method returns, shared will be 100000.
  4. Now, thread 2 acquires the lock and executes. At the end shared will be 100001.
  5. Thread 2 prints Thread2 End !!
  6. Thread 1 prints Thread1 End !!

At points 5 and 6 , value of shared is 100001. (You can reverse 5 and 6 too; the result would be the same).

The key is that thread 1 wasn't able to print before thread 2 increments as part of its execution. Thus, you see the same result for both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM