我想了解java中的同步。我有下面的例子中, for循環同步方法
public class TestThr implements Runnable {
public static void main(String[] args) {
Thread t=new Thread(new TestThr());
Thread t1=new Thread(new TestThr());
t.start();
t1.start();
}
@Override
public void run() {
sync();
}
public synchronized void sync(){
for (int i=0;i<10;i++){
System.out.println("Running "+Thread.currentThread().getName());
}
}
}
Output : Running Thread-0 Running Thread-1 Running Thread-0 Running Thread-1 Running Thread-0 Running Thread-1 Running Thread-1 Running Thread-1 Running Thread-0 Running Thread-1 Running Thread-1 Running Thread-1 Running Thread-1 Running Thread-1 Running Thread-0 Running Thread-0 Running Thread-0 Running Thread-0 Running Thread-0 Running Thread-0
從上面的例子,我期待一個線程(誰進入第一)將完成迭代,然後第二次將啓動並完成,但我得到不一致的輸出。
請加你的意見。
在此先感謝。
你搜索*堆棧溢出*爲的是什麼意思,同步的方法說明? – CKing
@CKing抱歉,但我無法理解同步方法的行爲。爲了澄清同樣的問題。 – dullpointer