public class TestThread {
    public static void main(String[] args){            MyThread t = new MyThread();
            t.start();
            System.out.println("3");
    }
}
class MyThread extends Thread{
    public void run(){
       System.out.println("2");
    }
}
为什么结果是先3 再2,怎么样才能先2 再3 阿?
不用 t.run()

解决方案 »

  1.   

    首先、先打印哪个是控制不了的
    用join()可以解决你的问题public class TestThread {
        public static void main(String[] args){
          MyThread t = new MyThread();
             t.start();
             try {
    t.join();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
             System.out.println("3");  
        }
    }
    class MyThread extends Thread{
        public void run(){
           System.out.println("2");
        }
    }
      

  2.   

    主线程执行完打印任务,MyThread还没获得系统分配的空闲,所以会像楼主的情况一样,2楼正解
      

  3.   

    public class TestThread {
        public static void main(String[] args) {            MyThread t = new MyThread();
                t.start();
                t.setPriority(8);
                System.out.println("3");
        }
    }
    class MyThread extends Thread{
        public void run(){
           System.out.println("2");
        }
    }
      

  4.   

    单纯的由执行时间所决定
    main()要是从1打印到1000
    那么 打印2 可能就出现在中间了
      

  5.   

    实际上我想写一个Server 监听socket,每收到一个连接就建一个线程负责监听。用join必须结束一个连接,才能收下一个。
      

  6.   

    //main方法也是一个线程Java codepublic class TestThread {
        public static void main(String[] args){            MyThread t = new MyThread();
                t.start();
                try{
                   Thread。sleep(2000);//mian线程睡2秒,这样main线程会让
                       出CPU,接着t线程得到CPU控制权,打印2
                }
                System.out.println("3");
        }
    }
    class MyThread extends Thread{
        public void run(){
           System.out.println("2");
        }
    这样就能先2 再打印3
    }
      

  7.   

    看看 Thread 的API 把自定义的线程的优先级设定一下 
      

  8.   


    public class test {
        public static void main(String[] args){            MyThread t = new MyThread();
                t.start();
                try{
                t.join();
                }
                catch(InterruptedException e){
                
                }
                System.out.println("3");
      }
    }
    class MyThread extends Thread{
        public void run(){
           System.out.println("2");
        }
    }