![](/img/trans.png)
[英]Given this outline what is wrong with the code I wrote? please be explicit in explaining why something doesn't work
[英]I have started learning synchronization in threading.I wrote some code.Why sometimes synchronized block doesn't work right?
我只是想用 2 個線程增加變量,但有時顯示值不正確。
public class SynchBlock {
public static void main(String[] args) throws InterruptedException {
SynchBlock obj= new SynchBlock();
obj.dowork();
}
}
同步塊的方法
private int count;
public void call() {
synchronized (this) {
count++;
}
}
SynchBlock 方法運行線程
public void dowork() throws InterruptedException {
th1.start();
th2.start();
th1.join();
th1.join();
System.out.println(count);
}
線程 class 1 只是增加計數值
Thread th1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
call();
}
}
});
線程 class 2 只是增加計數值
Thread th2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
call();
}
}
});
你不加入th2
。 您加入th1
兩次,因此有時您會在th2
完成之前打印count
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.