[英]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考虑以下操作序列
Thread1 Start !!
Thread1 Start !!
Thread2 Start !!
Thread2 Start !!
sharedIncrease
(Thread 2 is blocked).sharedIncrease
的逻辑(线程2被阻塞)。 When the method returns, shared
will be 100000.shared
将为 100000。shared
will be 100001.shared
将是 100001。Thread2 End !!
Thread2 End !!
Thread1 End !!
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).在点
5
和6
, shared
值为 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.