public class Thread1 extends Thread { String name; public Thread1(String name) { this.name=name; } public void run() { int i=1; while(i<=5) { System.out.println(name+"执行步骤"+i); i++; } } public static void main(String[] args) { Thread1 thread1=new Thread1("线程1"); thread1.setPriority(10); Thread1 thread2=new Thread1("线程2"); thread2.setPriority(1); thread1.start(); thread2.start(); } }
setPriority()方法设定线程的优先级仅表示此线程具有较多的执行机会,而非优先执行
运行结果
线程2执行步骤1
线程1执行步骤1
线程2执行步骤2
线程1执行步骤2
线程1执行步骤3
线程1执行步骤4
线程2执行步骤3
线程1执行步骤5
线程2执行步骤4
线程2执行步骤5
线程1执行步骤1
线程2执行步骤2
线程1执行步骤2
线程1执行步骤3
线程1执行步骤4
线程2执行步骤3
线程1执行步骤5
线程2执行步骤4
线程2执行步骤5