7.线程生命周期的相关方法:线程生命周期的相关方法有哪五个???
学习:第7遍
1.线程生命周期的相关方法有哪五个???
方法一:thread.start() 作用: 启动线程,线程进入就绪状态(可运行状态)
方法二:Thread.sleep() 作用:休眠线程,线程从执行状态进入阻塞状态 静态方法
方法三:Thread.yield() 作用:暂停执行线程,线程从执行状态进入就绪状态 静态方法 放弃当前CPU时间片,重新争抢
方法四:thread.join() 作用:暂停执行线程,等待另一个线程执行完毕后再执行,线程从执行状态进入阻塞状态
方法五:thread.interrupt() 作用:中断线程的休眠或等待状态
public class Test{
public static void main(String
[] args
) {
Thread t
= new Thread(new Runnable() {
@Override
public void run() {
for (int i
= 1; i
<= 50; i
++) {
if (i
== 8) {
try {
Thread
.sleep(5000);
} catch (InterruptedException e
) {
System
.out
.println(Thread
.currentThread().getName()+"被打断了");
}
}
System
.out
.println(Thread
.currentThread().getName()
+ "----" + i
);
}
}
}, "t");
t
.start();
try {
Thread
.sleep(2000);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
for (int i
= 1; i
<= 50; i
++) {
System
.out
.println(Thread
.currentThread().getName() + "----" + i
);
}
t
.interrupt();
}
}