多线程(7)线程礼让yield,强制执行join,线程优先级,守护线程
一:线程礼让
①礼让线程,让当前正在执行的线程暂停,但不阻塞
②将线程从运行状态转为就绪状态
③让cpu重新调度,礼让不一定成功,看cpu
其实yield的作用就是让我们的运行时的线程转变为就绪状态的线程,和那些就绪的线程一起竞争
class Yield implements Runnable{
public static void main(String[] args) {
Yield yield=new Yield();
new Thread(yield,"zph").start();
new Thread(yield,"wlw").start();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始了");
Thread.yield();//谁先执行后,就礼让其它的线程,但是不一定成功
System.out.println(Thread.currentThread().getName()+"结束了");
}
}
wlw开始了
zph开始了
wlw结束了
zph结束了
二:线程强制执行Join
①join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
②可以理解为插队
class Join implements Runnable{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new Join());
thread.start();
for (int j=0;j<1000;j++){
if (j==800){
thread.join();
}
System.out.println(Thread.currentThread().getName()+j);
}
}
}
如果我们的main线程先执行,那么当我们主线程执行到800次的时候,我们进行插队进行thread线程执行。
三:线程的优先级
①java提供了一个线程调度器来监控程序启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行。
②线程的优先级用数字表示,范围从1-10
Thread.MIN_PRIORITY=1;
Thread.MAX_PRIORITY=10;
③使用以下方式改变或获取优先级
getPriority(),setPriority(int i)
class TestPriority implements Runnable{
public static void main(String[] args) {
TestPriority testPriority=new TestPriority();
Thread thread=new Thread(testPriority,"zph");
Thread thread1=new Thread(testPriority,"wlw");
Thread thread2=new Thread(testPriority,"nyy");
Thread thread3=new Thread(testPriority,"lzh");
thread.setPriority(10);
thread1.setPriority(5);
thread2.setPriority(1);
thread3.setPriority(8);
thread.start();
thread1.start();
thread2.start();
thread3.start();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"---:"+Thread.currentThread().getPriority());
}
}
并不是优先级高的一定先执行
四:守护线程
①线程分为用户线程和守护线程
②虚拟机必须确保用户线程执行完毕
③虚拟机不用等待守护线程执行完毕
④如;后台记录操作日志,监控内存,垃圾回收等待
class TestDaemon {
public static void main(String[] args) {
You1 you1=new You1();
Tian tian=new Tian();
Thread thread=new Thread(tian);
thread.setDaemon(true);//将天设置为守护线程
thread.start(); //启动线程启动
new Thread(you1).start();//自己线程启动
}
}
class You1 implements Runnable{
@Override
public void run() {
for (int i=0;i<355;i++){
System.out.println("生活着:"+i);
}
System.out.println("我结束了");
}
}
class Tian implements Runnable{
@Override
public void run() {
while (true){
System.out.println("我是天");
}
}
}
浙公网安备 33010602011771号