
在对线程进行停止的使用,我们使用Thread类来进行操作,这里停止的状态分为三种:sleep、join和yield。它们都是使当前的线程停下来,不过在中断时有所区别。下面我们就java中Thread类的三种停止模式,分别带来概念和代码示例的讲解,一起看看都有哪些停止状态吧。
1.sleep
sleep()使当前线程进入停滞状态(阻塞当前线程),让出CPU的使用,以留一定时间给其他线程执行
sleep休眠时不会释放对象的锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class SleepDemo {
public static void main(String[] args) throws InterruptedException {
Process process = new Process();
Thread thread = new Thread(process);
thread.setName( "线程Process" );
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
Thread.sleep(1000);
}
}
}
class Process implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
2.join
在一个线程A中执行了线程B的join方法,则A会挂起,等待B执行完毕后再执行后续任务。
1 2 3 4 5 6 7 | public static void main(String[] args){
Thread t1 = new Thread();
t1.start();
t1.join();
System.out.println( "t1 finished" );
}
|
3.yield
yield并不意味着退出和暂停,是让步,告诉线程调度如果有人需要,可以先拿去,我过会再执行,没人需要,我继续执行。
调用yield的时候锁并没有被释放。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.yield;
public class YieldTest extends Thread {
public YieldTest(String name) {
super (name);
}
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
System.out.println( "" + this .getName() + "-----" + i);
if (i == 30) {
this .yield();
}
}
}
public static void main(String[] args) {
YieldTest yt1 = new YieldTest( "张三" );
YieldTest yt2 = new YieldTest( "李四" );
yt1.start();
yt2.start();
}
}
|
以上就是java中Thread的停止状态详解,根据需要我们可以在线程,停留在不同的状态中,学会的小伙伴可以分别尝试下代码部分的使用。