程序一:
  class TestThread implements Runnable {
  public void synchronized run() { // run()同步了;
    for(int i = 0; i < 5; i++) {
      System.out.println(Thread.currentThread().getName()+ " " + i);
    try {
      Thread.sleep(100);    } catch(InterruptedException e) {
      throw new RuntimeException(e);
    }
    }
  }  public static void main(String[] args) {
    TestThread test = new TestThread();//这里先产生一个implements了runnable的对象;
    for(int i = 0; i < 5; i++)
      new Thread(test, "t" + i).start();//每次产生的线程都是用同一个runnable对象;
  }
}
程序二;
class TestThread implements Runnable {
  public void synchroinzed run() {  //run() 同步了.
    for(int i = 0; i < 5; i++) {
      System.out.println(Thread.currentThread().getName()+ " " + i);
    try {
      Thread.sleep(100);    } catch(InterruptedException e) {
      throw new RuntimeException(e);
    }
    }
  }  public static void main(String[] args) {
   // TestThread test = new TestThread();
    for(int i = 0; i < 5; i++)
      new Thread(new TestThread(), "t" + i).start();//与程序一不同的是.每产生一个线程都用不同的rnnable对象;
  }
}
问题1:
t0 0
t0 1
t0 2
t0 3
t0 4
t1 0
t1 1
t1 2
t1 3
t1 4
t2 0
t2 1
t2 2
t2 3
t2 4
程序一的输出如上(部分省略了)t0 0
t1 0
t2 0
t3 0
t4 0
t0 1
t1 1
t2 1
t3 1
t4 1
程序二就可以实现了多线程.问题2:
去掉了synchronized之后.不论哪个程序,都可以实现多线程
请帮忙解释一下,谢谢:)

解决方案 »

  1.   

    楼主好象多线程的概念并没有搞清,另外public void synchronized run()中synchronized位置错误
      

  2.   

    楼主把synchronized放到void前面先
    解释:
    第一个程序,new Thread(test, "t" + i).start();//每次产生的线程都是用同一个runnable对象;
    在循环过程中,一次允许一个线程run,因为是synchronized,所以每次一个线程run完(一次输完方法里的System.out.println(Thread.currentThread().getName()+ " " + i);)之后再进入下一轮循环的run,这个过程中,第二个线程一直在等待第一个线程的结束第二个程序,建议楼主把主函数里的循环次数设大一点,比如500,效果会更明显,其实就是自己管自己
      

  3.   

    synchronized 位置是放错了...粘贴时错了位置...
    谢谢指教.