- class Machine extends Thread
- {
- int i=0;
- static StringBuffer str=new StringBuffer();
- public void run(){
- for(;i<10;i++){
- //str字符串存储当前运行的线程名称
- str.append("执行线程"+Thread.currentThread().getName()+"\n");
- }
- }
- };
- class MachineMain
- {
- public static void main(String[] args)
- {
- Machine m1=new Machine();
- Machine m2=new Machine();
- m1.setName("A");//设置线程名字
- m2.setName("B");
- //打印各个线程的默认优先级
- System.out.println(m1.getName()+"线程默认优先级"+m1.getPriority());
- System.out.println(Thread.currentThread().getName()+"线程默认优先级"+m1.getPriority());
- System.out.println(m2.getName()+"线程默认优先级"+m2.getPriority());
- //对m1m2线程设置最大、最小优先级
- m1.setPriority(Thread.MAX_PRIORITY);
- m2.setPriority(Thread.MIN_PRIORITY);
- //打印修改优先级后的各个线程的优先级
- System.out.println(m1.getName()+"线程优先级"+m1.getPriority());
- System.out.println(Thread.currentThread().getName()+"线程优先级"+Thread.currentThread().getPriority());
- System.out.println(m2.getName()+"线程优先级"+m2.getPriority());
- //启动线程
- m1.start();
- m2.start();
- //当m1m2线程存活时主线程休眠500毫秒
- while(m1.isAlive()||m2.isAlive())
- try{Thread.sleep(500);}catch(InterruptedException e){}
- //打印str字符串
- System.out.println(Machine.str);
- }
- }
复制代码
如上面代码,我已经将M1的优先级设置为最大、M2的优先级设置为最小,按道理来讲应该先执行M1再执行M2,为什么是这个结果?
A.B线程为什么仍然交替执行?
|
|