通知线程终止和中断 --贰
基本说明:
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");
}
}
}
}
根据韩顺平老师课程做的笔记!!!