在java中,thread类是多线程编程的核心。
线程创建 (thread creation)
- 创建线程主要有两种逻辑:继承thread类或实现runnable接口。
- 方式1:继承 thread 类,重写run()
// 自定义线程类继承thread
class mythread extends thread {
// 重写run(),定义线程执行逻辑
@override
public void run() {
system.out.println("子线程执行:" + thread.currentthread().getname());
}
}
// 使用
public class demo {
public static void main(string[] args) {
mythread t = new mythread();
t.start(); // 3. 调用start()启动线程(不能直接调用run())
}
}
- 方式2:实现runnable接口,传给thread
// 实现runnable接口
class myrunnable implements runnable {
@override
public void run() {
system.out.println("子线程执行:" + thread.currentthread().getname());
}
}
// 使用
public class demo {
public static void main(string[] args) {
// 把runnable实例传给thread
thread t = new thread(new myrunnable());
t.start(); // 启动线程
}
}
线程中断 (thread interruption)
- 线程中断不是强制停止线程,而是一种协作机制,即给线程发一个“请停止”的信号。
- void interrupt():标记线程为 “中断状态”
- boolean isinterrupted():判断线程是否处于中断状态
- 若线程在sleep/wait/join时被中断,会抛出interruptedexception,且中断状态会被清除
thread t = new thread(() -> {
while (!thread.currentthread().isinterrupted()) { // 检测中断状态
system.out.println("线程运行中...");
try {
thread.sleep(1000);
} catch (interruptedexception e) {
// 捕获中断异常后,中断状态会被清除,需手动终止循环
system.out.println("线程被中断");
thread.currentthread().interrupt(); // 重新标记中断(可选)
break;
}
}
});
t.start();
// 主线程1秒后中断子线程
thread.sleep(1000);
t.interrupt();
线程等待 (thread join)
- 有时主线程需要等待子线程执行完毕后再继续执行,这时可以使用join()。
- t.join():当前线程会进入阻塞状态,直到线程t执行结束。
- 带参数的 join(long millis):设置最大等待时间,如果超时线程还没结束,当前线程就不再等待。
thread t = new thread(() -> {
system.out.println("子线程开始执行");
try { thread.sleep(2000); } catch (interruptedexception e) {}
system.out.println("子线程执行完毕");
});
t.start();
// 主线程等待t执行完(最多等3秒)
t.join(3000);
system.out.println("主线程继续执行");
线程休眠 (thread sleep)
- static void sleep(long millis):让当前线程暂停指定时间(不会释放锁),抛出interruptedexception
system.out.println("开始休眠");
try {
thread.sleep(2000); // 当前线程休眠2秒
} catch (interruptedexception e) {
e.printstacktrace();
}
system.out.println("休眠结束");
获取线程实例 (get current instance)
- 在编写通用代码(尤其是 runnable 中)时,常需要知道是谁在运行。
- thread.currentthread():返回代码当前正在执行的那个线程对象的引用。
- 常用操作:获取线程 id (getid())、获取线程名称 (getname()) 等。
// 获取当前线程(这里是main线程)
thread mainthread = thread.currentthread();
system.out.println("当前线程名:" + mainthread.getname()); // 输出"main"
// 子线程实例
thread t = new thread(() -> {
thread current = thread.currentthread();
system.out.println("子线程名:" + current.getname()); // 输出"thread-0"
});
t.start();
java线程的几种状态
线程状态一共有几种?
- java线程共有6种状态:
- new (新建)
- runnable (可运行)
- blocked (阻塞)
- waiting (等待)
- timed_waiting (超时等待)
- terminated (终止)
每种状态的含义与切换条件
- new (新建)
- 含义:创建了线程对象(new thread()),但尚未调用 start() 方法。
- 切换:调用 start() 方法后,进入 runnable 状态。
- runnable (可运行)
- 含义:java 将操作系统中的“就绪(ready)”和“运行中(running)”两种状态统称为 runnable。处于该状态的线程可能正在 cpu 上执行,也可能正在等待操作系统分配时间片。
- 切换:
- 就绪 -> 运行:获得 cpu 时间片。
- 运行 -> 就绪:cpu 时间片用完,或主动调用 thread.yield()。
- blocked (阻塞)
- 含义:线程正在等待获取一个排他锁(如进入synchronized 代码块/方法),但该锁目前被其他线程持有。
- 切换:
- runnable -> blocked:尝试进入 synchronized 区域失败。
- blocked -> runnable:其他线程释放锁,当前线程成功竞争到锁。
- waiting (等待)
- 含义:线程处于无限期的等待状态,不会被分配 cpu 时间,必须等待其他线程显式地唤醒。
- 切换:
- runnable -> waiting:调用 object.wait()(不带参数)、thread.join()(不带参数)或 locksupport.park()。
- waiting -> runnable:其他线程调用 object.notify()、notifyall() 或 locksupport.unpark()。
- timed_waiting (超时等待)
- 含义:与 waiting 类似,但在指定的时间后会自动唤醒,不需要其他线程显式唤醒。
- 切换:
- runnable -> timed_waiting:调用 thread.sleep(ms)、object.wait(ms)、thread.join(ms) 等带时间参数的方法。
- timed_waiting -> runnable:时间结束,或被提前唤醒(如 notify())。
- terminated (终止)
- 含义:线程已经执行完毕(run() 方法正常结束)或因异常退出了执行。
- 切换:线程一旦进入此状态,生命周期结束,不可再次启动(再次调用 start() 会抛出异常)。
总结
到此这篇关于thread类基本用法及java线程几种状态的文章就介绍到这了,更多相关thread类用法及java线程状态内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论