线程优先级

多线程运行时需要定义线程运行的先后顺序。

线程优先级是用数字表示,数字越大线程优先级越高,取值在110,默认优先级为5

实例:

package com.bijian.study;

/**
 * 因为在代码段当中把线程B的优先级设置高于线程A,所以运行结果先执行线程B的run()方法后再执行线程A的run()方法
 * 但在实际中,JAVA的优先级不准,强烈不建议用此方法来控制执行顺序和频率
 */
public class ThreadPriorityDemo {

	public static void main(String args[]) {
		ThreadA a = new ThreadA();
		ThreadB b = new ThreadB();
		b.setPriority(10);
		a.setPriority(1);	//设置优先级别,数值越大优先级越高
		
		int priA = a.getPriority();	//获得优先级的方法
		int priB = b.getPriority();
		System.out.println(priA);
		System.out.println(priB);
		
		b.start();
		a.start();
	}
}

class ThreadA extends Thread {
	public void run() {
		System.out.println("我是线程A");
	}
}

class ThreadB extends Thread {
	public void run() {
		System.out.println("我是线程B");
	}
}

 运行结果:

1
10
我是线程B
我是线程A

设置优先级也可以用线程常量

a.       MAX_PRIORITY为最高优先级10

b.       MIN_PRIORITY为最低优先级1

c.       NORM_PRIORITY是默认优先级5

实例:

package com.bijian.study;

public class ThreadPriConstantDemo {

	public static void main(String args[]) {
		Thread a = new Thread();
		int temp = Thread.MAX_PRIORITY;
		a.setPriority(temp);	//将线程优先级设置为最高
		System.out.println(a.getPriority());
		
		temp = Thread.MIN_PRIORITY;
		a.setPriority(temp);	//将线程优先级设置为最低
		System.out.println(a.getPriority());
		
		temp = Thread.NORM_PRIORITY;
		a.setPriority(temp);	//将线程优先级设置为默认
		System.out.println(a.getPriority());
	}
}

运行结果:

10
1
5

 

你可能感兴趣的:(java,thread,多线程,java多线程)