简体   繁体   English

我不知道为什么这些输出出来,(java线程)

[英]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...我认为输出是 {1,10001} 或 {10000,10001} 因为同步...

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.线程 1 开始。 Prints Thread1 Start !!打印Thread1 Start !!
  2. Thread 2 starts.线程 2 开始。 Prints Thread2 Start !!打印Thread2 Start !!
  3. Thread 1 acquires the lock and executes the logic in sharedIncrease (Thread 2 is blocked).线程1获取锁并执行sharedIncrease的逻辑(线程2被阻塞)。 When the method returns, shared will be 100000.当方法返回时, shared将为 100000。
  4. Now, thread 2 acquires the lock and executes.现在,线程 2 获取锁并执行。 At the end shared will be 100001.最后shared将是 100001。
  5. Thread 2 prints Thread2 End !!线程 2 打印Thread2 End !!
  6. Thread 1 prints Thread1 End !!线程 1 打印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).在点56shared值为 100001。(您也可以将 5 和 6 颠倒;结果是相同的)。

The key is that thread 1 wasn't able to print before thread 2 increments as part of its execution.关键是线程 1 无法在线程 2 作为其执行的一部分递增之前打印。 Thus, you see the same result for both.因此,您会看到两者的结果相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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