1、线程常用的方法
start() ①启动当前线程 ②调用当前线程的run()方法
run(),通常需要重写Thread类中的此方法,将创建的线程的声明要执行的操作声明在此方法中
currentThread():静态方法,返回当前代码执行的线程
getName()获取当前线程的名字
setNmae()设置当前线程的名字
yield() 释放当前cpu的执行权,线程礼让(不一定成功)
join() 在线程A中调用线程B的join()方法,则线程A进入阻塞状态,直到线程B执行完以后线程A才结束阻塞状态
stop() 强制结束当前线程(不建议使用)
sleep(Long millitime) 让当前线程“睡眠”,,指定毫秒内线程是阻塞状态
isAlive()判断当前线程是否还存活
2、线程优先级设置
2.1 线程的优先级
MAX_PRIORITY : 10
MIN_PRIORITY : 1
NORM_PRIORITY : 5 默认优先级
2.2 获取或者设置当前线程的优先级
getPriority(int p); 获取线程的优先级
setPriority(int p); 设置线程的优先级
高优先线程会抢占低优先级的CPU的执行权,只是从概率上讲,但不一定成功
3、代码实例
package Thread;
/**
* 测试Thread中常用的方法
* 1.start() ①启动当前线程 ②调用当前线程的run()方法
* 2.run(),通常需要重写Thread类中的此方法,将创建的线程的声明要执行的操作声明在此方法中
* 3.currentThread():静态方法,返回当前代码执行的线程
* 4.getName()获取当前线程的名字
* 5.setNmae()设置当前线程的名字
* 6.yield() 释放当前cpu的执行权,线程礼让(不一定成功)
* 7.join() 在线程A中调用线程B的join()方法,则线程A进入阻塞状态,直到线程B执行完以后线程A才结束阻塞状态
* 8.stop() 强制结束当前线程(不建议使用)
* 9.sleep(Long millitime) 让当前线程“睡眠”,,指定毫秒内线程是阻塞状态
* 10.isAlive()判断当前线程是否还存活
*
* 线程的优先级
* MAX_PRIORITY : 10
* MIN_PRIORITY : 1
* NORM_PRIORITY : 5 默认优先级
* 获取或者设置当前线程的优先级
* getPriority(int p); 获取线程的优先级
* setPriority(int p); 设置线程的优先级
*
* 高优先线程会抢占低优先级的CPU的执行权,只是从概率上讲,但不一定成功
*
*
* @author Muluo
* @create 2021-01-17 20:52
*/
public class ThreadMethodTest {
public static void main(String[] args) {
// 设置线程名 方式二用构造器方法设置
HelloThread helloThread = new HelloThread("Thread一");
// 设置线程名 方式一用get/set方法设置
// helloThread.setName("线程一");
// 设置当前线程的优先级,在start()之前
// helloThread.setPriority(Thread.MAX_PRIORITY);
helloThread.setPriority(1);
helloThread.start();
// 给主线程设置别名
Thread.currentThread().setName("主线程");
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
// CTrl + Shift 上下键
System.out.println(Thread.currentThread().getName() + " " +i);
}
if (i == 20) {
try {
helloThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 判断线程是否还存活
System.out.println(helloThread.isAlive());
// 获取当前线程的优先级
System.out.println(helloThread.getPriority());
}
}
class HelloThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
// 父类run()方法没有抛异常,所以此时只能用try/catch处理异常,且子类的异常不能比父类所掏出的异常大
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// CTrl + Shift 上下键
System.out.println(Thread.currentThread().getName() + " " +i);
}
if (i % 20 == 0) {
// yield()省略this
yield();
}
}
}
public HelloThread(String name) {
// 调用父类的构造器,用来给当前线程设置别名
super(name);
}
}