不会还不知道通知线程终止吧!

通知线程终止和中断 --贰

基本说明:

1、当线程完成任务 会自动退出

2、还可以通过使用变量来控制run方法退出得方式 停止线程 即 通知方式

package com.company.duoxiancheng.review;

public class ThreadExit_ {
    public static void main(String[] args) {
        T t1 = new T();
        t1.start();
        t1.Setloop(false);
        //如果希望main线程去控制t1 线程的
    }
}
class T extends Thread{
    private int num =0;
    private boolean loop = true;
    int count = 0;
    public void Setloop(boolean loop){
        this.loop = loop;
    }
    @Override
    public void run() {
        while (loop){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("T,还在运行中");
        }
    }
}
线程的常用方法

priority :优先级

1、setName //设置线程名称 使之与参数name相同

2、getName //返回该线程的名称

3、start //使该线程开始执行 Java虚拟机底层调用该线程的Start0方法

4、run //调用线程对像run方法

5、setPriority //更改线程的优先级

6、getPriority //获取线程的优先级

7、sleep //在指定的毫米数内让当前正在执行的线程休眠(暂停执行)

8、interrupt //中断线程

注意和细节

在这里插入图片描述

 /**
  * The minimum priority that a thread can have.
  */
 public final static int MIN_PRIORITY = 1;

/**
  * The default priority that is assigned to a thread.
  */
 public final static int NORM_PRIORITY = 5;

 /**
  * The maximum priority that a thread can have.
  */
 public final static int MAX_PRIORITY = 10;

在中断截至时候的进行添加自己的业务逻辑代码

当该线程执行到了一个interrupt方法时 kcatch一个异常可以加入自己的业务代码
捕获中断异常
package com.company.duoxiancheng.review;

public class ThreadMethod01 {
    public static void main(String[] args) throws InterruptedException {
        T10 t100 = new T10();
        t100.setName("lsp");
        t100.setPriority(Thread.MIN_PRIORITY);
        t100.start();
        //主线程打印 5 hi 然后就中断子线程休眠
        for(int i=0;i<5;i++){
            Thread.sleep(1000);
            System.out.println("hi"+i);
        }
        System.out.println(t100.getName()+"的优先级"+t100.getPriority());
        t100.interrupt(); //当执行到这里就会中断休眠 t线程的休眠
    }
}
class T10 extends Thread{
    @Override
    public void run() {
        while (true){
        for (int i = 0; i <100 ; i++) {
            System.out.println(Thread.currentThread().getName()+"吃包子"+i);
        }
        try {
            System.out.println(Thread.currentThread().getName()+"休眠中");
            Thread.sleep(20000);
        } catch (InterruptedException e) {

            //当该线程执行到了一个interrupt方法时 空i囧catch一个异常可以加入自己的业务代码
            //捕获中断异常
            System.out.println(Thread.currentThread().getName()+"被interrupt");
        }
        }
    }
}

根据韩顺平老师课程做的笔记!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值