小编Bha*_*Vre的帖子

同步方法中的for循环

我试图理解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 …

java multithreading synchronization

1
推荐指数
1
解决办法
1941
查看次数

标签 统计

java ×1

multithreading ×1

synchronization ×1