【线程】线程合并、线程优先级

线程合并

  • 线程中join方法的意思是把指定的线程加入到当前线程,即将两个交替执行的线程合并为顺序执行的线程。比如在主线程B中,子线程A调用了join()方法,意思是说直到线程A执行完毕后,线程B才会继续执行。同理,如果子线程A调用了join(10)方法,意思是说等线程A执行10毫秒后,线程B才会继续执行;
  • 合并线程是加入到启动线程的这个线程里,主线程等待加入线程执行完执行。

代码展示:

package edu.xalead;

//class T4 implements Runnable{
//    @Override
//    public void run() {
//
//        while(true){
//            System.out.println(Thread.currentThread().getName());
//        }
//    }
//}

class T9 extends Thread{

    T9(){
        /*super*/this.setName("合并线程");   //给线程起名字
    }
    @Override
    public void run() {
        while(true){
            System.out.println(this.getName());
        }
    }
}

public class 加入 {
    public static void main(String[] args)throws InterruptedException {
//        Thread t = new Thread(new T4());
//        t.start();

        T9 t1 = new T9();
        t1.start();
        //t1.join();

        //t.join();    //主线程等着t线程执行完
        while(true){
            System.out.println(Thread.currentThread().getName());
        }
    }

运行结果:
在这里插入图片描述

主线程和T9线程执行概率各位1/2

线程的优先级:
优先级高则获得执行时间多,相反若优先级低则获得的执行时间少。 在这里插入图片描述
运行代码:

package edu.xalead;
class TS implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println(Thread.currentThread().getName());
        }
    }
}

public class 线程的优先级 {
    public static void main(String[] args) {

        Thread t = new Thread(new TS(),"A");
        Thread t1 = new Thread(new TS(),"B");
        Thread t2 = new Thread(new TS(),"C");

        t.setPriority(Thread.MAX_PRIORITY);
        t1.setPriority(Thread.NORM_PRIORITY);
        t2.setPriority(Thread.MIN_PRIORITY);

        t.start();
        t1.start();
        t2.start();
       //优先级在start之后使用没有作用,须在Start之前使用

    }
}

运行结果:
在这里插入图片描述
执行顺序是A,B,C.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值