我试图理解java中的同步。我有以下示例
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出: 运行线程-0 运行线程1 运行线程-0 运行线程1 运行线程-0 运行线程1 运行线程1 运行线程1 运行线程-0 运行线程1 运行线程1 运行线程1 运行线程1 运行线程1 运行线程-0 运行线程-0 运行线程-0 运行线程-0 运行线程-0 运行线程-0
From above example I was expecting one thread(whoever enter first) will complete the iteration and then …