1
這裏是我的類哪一次調用線程獲取對象的內部鎖?
public class ThreadTest {
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.m1();
synchronized (threadTest) {
threadTest.m2();
}
System.out.println("End of main thread");
}
public void m1() {
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
System.out.println("end of mythread");
}
});
myThread.start();
}
public void m2() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
雖然我把我的代碼裏面塊它似乎沒有正常工作,既for
環體運行parallelly.How我可以運行這些循環的線程在多線程環境與同步塊。我給我的代碼給出錯誤的地方在哪裏?
謝謝!
+1總之,每個線程必須在同一個對象上有一個同步塊來查看OP的期望。你可以使m2()同步並在m1中有線程,調用m2(); –
yes.i檢查了。感謝JB和Peter乾淨而快速的回覆:) –