- package thread;
- public class SecondThread implements Runnable
- {
- private int i;
-
- public void run()
- {
- for (;i < 1000;i++)
- synchronized(this){
- System.out.println(Thread.currentThread().getName() + " " + i);
- }
- }
-
- public static void main(String[] args)
- {
- for (int i = 0;i < 100;i++)
- {
- System.out.println(Thread.currentThread().getName() + " " + i);
-
- if (i == 20)
- {
- SecondThread st = new SecondThread();
-
- new Thread(st,"新线程1").start();
- new Thread(st,"新线程2").start();
- }
- }
- }
- }
复制代码 对共享资源上锁可以消除你所说的情况,至于你说的为什么总是在第一次切换时出现,观望中.... |