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
Thread1 Start !!
Thread2 Start !!
sharedIncrease
(Thread 2 is blocked). When the method returns, shared
will be 100000.shared
will be 100001.Thread2 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).
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.