QJ02. 有如下测试synchronized关键字作用的程序,程序希望通过得到如下输出证明synchronized代码块同时只能被一个线程访问。
但是现在程序的输出并不让人满意,请找出问题原因,并改正之。
希望得到的输出
A0
A1
A2
B0
B1
B2程序代码public class ThreadTest implements Runnable {
public void run() {
synchronized (this) {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();

System.out.println(Thread.currentThread().getName() + i);
}
}
}
public static void main(String[] args) {
Thread ta = new Thread(new ThreadTest(), "A");
Thread tb = new Thread(new ThreadTest(), "B");
ta.start();
tb.start();
}
}

解决方案 »

  1.   

    public class ThreadTest implements Runnable
    {
        public void run()
        {
            synchronized (this)
            {
                for (int i = 0; i < 3; i++)
                {
    //                try
    //                {
    //                    Thread.sleep(100);
    //                }
    //                catch (InterruptedException e)
    //                {
    //                    e.printStackTrace();
    //                }
                    System.out.println(Thread.currentThread().getName() + i);
                }
            }
        }    public static void main(String[] args)
        {
            Thread ta = new Thread(new ThreadTest(), "A");
            Thread tb = new Thread(new ThreadTest(), "B");
            ta.start();
            tb.start();
        }
    }
    Thread.sleep(100);把这个去掉,这个是让线程休眠,当A sleep后,自然就轮到B了。所以出现上面的结果。
      

  2.   

    如果想要 Thread.sleep(100);这句,就把它放循环外面。
      

  3.   

    非常感谢啊!还有一点不明白 为什么放在循环里就行 循环外就可以了呢 
    在循环里A sleep后,然后就轮到B了
    那么在外面就不一样吗?