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

关于Java线程优先级
Java code
class ThreadUse implements Runnable{
    public String name="";
    public ThreadUse(String str)
    {
        this.name=str;
    }
    public void run()
    {
        System.out.println("ThreadUse1 is running...");
        for(int i=0;i<10;i++)
        {
            System.out.println(name+":"+i);
        }
        System.out.println(name+":I am the end!");
    }
}

class ThreadUse2 extends Thread{
    private String name = "";
    public ThreadUse2(String str){
        name= str;
    }
    public void run(){
        System.out.println("ThreadUse2 is running...");
        for(int i=0;i<10;i++)
        {
            System.out.println(name+":"+i);
        }
        System.out.println(name+":I am the end!");
    }
}
public class Contest {
    public static void main(String args[])
    {
        //Runnable接口类的对象创建线程
        Thread number1 = new Thread(new ThreadUse("number1"));
        //Thread类的子类创建线程
        ThreadUse2 number2 = new ThreadUse2("number2");
        number1.setPriority(4);
        number2.setPriority(4);
        number1.start();
        number2.start();
        
    }
}


我将number1和number2的优先级设置成不同可以实现运行的优先顺序,但是相同的优先级为什么number1先执行呢?
ThreadUse1 is running...
number1:0
number1:1
number1:2
number1:3
number1:4
number1:5
number1:6
number1:7
number1:8
number1:9
number1:I am the end!
ThreadUse2 is running...
number2:0
number2:1
number2:2
number2:3
number2:4
number2:5
number2:6
number2:7
number2:8
number2:9
number2:I am the end!


我用的是MyEclips 8.0

------解决方案--------------------
在run()里加个sleep()就会有效果了,否则时间太短,一般先启动哪个就会先输出哪个