日期:2014-05-20  浏览次数:20692 次

问个Thread的小问题
Java code
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()

------解决方案--------------------
首先、先打印哪个是控制不了的
用join()可以解决你的问题
Java code

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");
    }
}

------解决方案--------------------
主线程执行完打印任务,MyThread还没获得系统分配的空闲,所以会像楼主的情况一样,2楼正解
------解决方案--------------------
Java code
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");
    }
}

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

------解决方案--------------------
//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
}