public class TT implements Runnable { int b = 100;
 public synchronized void m1() throws Exception {  // Thread.sleep(2000);
  System.out.println("m11");
  b = 1000;  Thread.sleep(5000);  System.out.println("m12"); }
 public synchronized void m2() throws Exception {
  System.out.println("m21");
  Thread.sleep(2500);
  b = 2000;
  System.out.println("m22");
 } public void run() {  try {
   System.out.println("run");
   m1();
  } catch (Exception e) {   e.printStackTrace();  } } public static void main(String[] args) throws Exception {  TT tt = new TT();  Thread t = new Thread(tt);  t.start();//run();  tt.m2();  System.out.println(tt.b); }}请问为什么运行的结果是m21   run  m22   m11  1000  m12
run()比m2()还慢运行????

解决方案 »

  1.   

    这个多线程的时候并不能看表面上应该是谁运行的,因为一旦是多线程就涉及到抢占CPU以及其他资源的问题,虽然你启动了线程,然后系统的确是会去执行run方法,但是并不能保证把run方法里的全部语句都执行完,也有可能是在执行run方法里的m1方法之前CPU就被分配去执行m2方法了的,就想操作系统里的时间片的那种说法哈~一个时间片结束了,但是这个方法还没执行完照样也会去执行其他线程里的语句的呢~
      

  2.   

    http://blog.csdn.net/mengxiangyue/article/details/6871219
    线程同步问题
      

  3.   

    t线程 比main线程慢是正常的。t是在main中启动的。
      

  4.   

    这个跟cpu设定的时间片有关系应该是,main线程先使用一个时间片执行了System.out.println("m21");
    然后轮到t.start()去执行System.out.println("run");
    每次都是main先使用一个时间片,然后才是启动的线程
      

  5.   

    关键在于理解synchronized(同步)。m1和m2都加synchronized运行时必须先m2运行完结,再运行m1。m1或者m2其中一个不加synchronized运行不需要“等”