- setName :设置线程名称,使之与参数 name 相同
- getName:返回该线程的名称
- start:使该线程开始执行,Java虚拟机底层调用该线程的 start0 方法
- run:调用线程对象 run 方法;
- setPriority:更改线程的优先级
- getPriority:获取线程的优先级
- sleep:在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)
- interrupt:中断线程,(提前结束休眠状态)
使用细节
- start:底层会创建新的线程,调用 run,run 就是一个简单的方法调用,不会启动新线程
- 线程优先级的范围
- interrupt:中断线程,但并没有真正的结束线程。所以一般用于中断正在休眠线程
- sleep:线程的静态方法,使当前线程休眠
package thread_;
public class Thread06 {
public static void main(String[] args) throws InterruptedException {
Thre thre = new Thre();
thre.setName("Gin");
thre.setPriority(Thread.MIN_PRIORITY);
thre.start(); // 启动线程
// 主线程打印 5 个 hi,就中断子线程的休眠
for (int i = 1; i <= 5; i++){
Thread.sleep(1000);
System.out.println(" hi " + i);
}
// 获取线程的优先级
System.out.println(thre.getName() + " 的优先级 " + thre.getPriority());
// 当执行到这里,就会中断 thre 线程的休眠
thre.interrupt();
}
}
class Thre extends Thread{ // 自定义的线程类
@Override
public void run() {
while (true){
for (int i = 1; i <= 100 ; i++){
System.out.println(Thread.currentThread().getName() + " 吃包子..." + i);
}
try {
System.out.println("休眠 20 秒...");
Thread.sleep(20000);
} catch (InterruptedException e) {
// 当该线程执行到一个 interrupt 方法时,就会 catch 一个 InterruptedException
// 可以加入自己的业务代码
System.out.println(Thread.currentThread().getName() + " 线程被中断了...");
}
}
}
}
线程常用方法(2)
- yield:线程的礼让。让出 cpu,让其他线程执行,但礼让的时间不确定,所以也不一定礼让成功 【 t1 礼让 cpu 资源执行 t2,调用 t1.yield()】
- join:线程的插队。插队的线程一旦插队成功,则肯定先执行完插入的线程所有的任务【t1 执行时,t2 插队,调用 t2.join()】
案例:main 线程创建一个子线程,每隔 0.5秒 输出 hello,输出 20次,主线程每隔 0.5秒,输出 hi,输出 20次。要求:两个线程同时执行,当主线程输出 5次 后,就让子线程运行完毕,主线程再继续。
package thread_;
public class Thread07 {
public static void main(String[] args) throws InterruptedException {
Thr thr = new Thr();
thr.start();
for (int i = 1; i <= 20; i++) {
Thread.sleep(500);
System.out.println("主线程吃了 " + i + " 个包子");
if (i == 5){
System.out.println("主线程让子线程先吃...");
thr.join();
System.out.println("子线程吃完了,主线程吃...");
}
}
}
}
class Thr extends Thread{
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + " 吃了 " + i + " 个包子");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
终止线程
终止线程
package thread_;
public class Thread05 {
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.start();
// 如果希望 main 线程控制 t 线程的终止,必须可以修改 flag
// 让 t 退出 run 方法,从而终止 t 线程
// 让主线程休眠 8 秒,再通知 t 线程退出
System.out.println("让主线程休眠 8 秒");
Thread.sleep(8 * 1000);
t.setFlag(false);
}
}
class T extends Thread{
private int count = 0;
private boolean flag = true;
@Override
public void run() {
while (flag){
System.out.println("子线程 T 在运行... " + (++count));
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}



