join方法
方法介绍:(强制执行)
1、在那个方法中调用就会阻塞哪个线程,不会阻塞别的线程。
2、在B线程中调用A.join();就会强制A线程执行,直到A线程执行完毕,B线程才有抢占CPU的权利,这过程中A,B之外的线程不受影响,依然可以和A线程抢占CPU使用权。
sleep方法
方法介绍:(休眠)
使当前正在执行的线程休眠millis秒,线程处于阻塞状态。
yield方法
方法介绍:(暂停)
当前线程暂停一次,让出CPU使用权,进入就绪状态,如果没有其他线程,本线程马上恢复执行。
线程优先级
获取线程优先级的几个方法:
1、线程名.getPriority()——获取线程优先级
2、线程名.setPriority()——设置线程优先级
3、MAX_PRIORITY——最大优先级(10)
3、MIN_PRIORITY——最小优先级(1)
4、NORM_PRIORITY——默认优先级(5)
代码样例
public class a_Priority {
public static void main(String[] args) {
System.out.println("最小优先级:"+Thread.MIN_PRIORITY);
System.out.println("默认优先级:"+Thread.NORM_PRIORITY);
System.out.println("最大优先级:"+Thread.MAX_PRIORITY);
Thread thread = Thread.currentThread();
System.out.println("主线程优先级:"+thread.getPriority());
//创建线程
MyThread myThread = new MyThread();
Thread thread2 = new Thread(myThread);
thread2.setPriority(2);
System.out.println("新创建的线程优先级:"+thread2.getPriority());
}
}
class MyThread implements Runnable{
@Override
public void run() {
// TODO 自动生成的方法存根
}
}