暂停线程执行sleep_yield_join_stop

时间:2023-03-09 08:40:26
暂停线程执行sleep_yield_join_stop

1.final void join() 调用该方法的线程强制执行完成,其它线程处于阻塞状态,该线程执行完毕,其它线程再执行

 public class TestJoin {
public static void main(String[] args) throws InterruptedException {
//主线程
MyThread my=new MyThread();
Thread t=new Thread(my);
Thread t2=new Thread(my);
//启动线程
t.start();
t2.start();
//以下代码为主线程中的循环
for(int i=0;i<5;i++){
if(i==2){
t.join(); //t线程强制执行
}
System.out.println("------------"+Thread.currentThread().getName()+"-------->"+i);
}
}
/**
* 导致调用它的线程进入阻塞状态,而不会导致其它的线程
*
* */
}

暂停线程执行sleep_yield_join_stop

main执行到2进入阻塞,等Thread-0和Thread-1执行完毕

--------------------------------------------------------------------------------------------------------------

2.static void sleep(long millis)  使当前正在执行的线程休眠millis毫秒,线程处于阻塞状态

 public class MyThread2 implements Runnable {
@Override
public void run() {
try {
System.out.println("MyThread2.run(),线程开始休眠");
Thread.sleep(3000);//休眠3秒
System.out.println("MyThread2.run(),休眠结束");
} catch (InterruptedException e) {
System.out.println("MyThread2.run(),产生异常");
}
}
}
 public class TestSleep2 {
/**
* sleep方法会导致线程进入阻塞,写在哪个线程体中就会导致哪个线程进入阻塞状态*/
public static void main(String[] args) throws InterruptedException {
MyThread2 my=new MyThread2();
Thread t=new Thread(my);
//启动线程
t.start();
//以下代码为主线程中的代码
System.out.println("主线程开始休眠");
Thread.sleep(2000);
System.out.println("主线程休眠结束");
}
}

暂停线程执行sleep_yield_join_stop

-------------------------------------------------------------------------------------------------------------------

3.static void yield()  当前正在执行的线程暂停一次(礼让),允许其他线程执行,不阻塞,线程进入就绪状态,如果没有其他等待执行的线程,这个时候当前线程就会马上恢复执行

 public class MyThread3 implements Runnable {
@Override
public void run() {
for(int i=0;i<5;i++){
if(i==2){
Thread.yield();//i==2时礼让一次
System.out.println("当前线程:"+Thread.currentThread().getName()+"线程礼让一次");
}
System.out.println("i="+i);
}
}
}
 public class TestYield {
public static void main(String[] args) {
MyThread3 my=new MyThread3();
new Thread(my).start();//启动线程
//主线程中的循环
for(int i=0;i<5;i++){
if(i==3){
Thread.yield();//i==3 主线程礼让一次
System.out.println(Thread.currentThread().getName()+"线程礼让一次");
}
System.out.println(Thread.currentThread().getName()+"------------"+i);
}
}
}

暂停线程执行sleep_yield_join_stop

--------------------------------------------------------------------------------------------------

4.final void stop()  强迫线程停止执行,已过时,不推荐使用

 public class MyThread4 implements Runnable {
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("i="+i);
}
}
}
 public class TestStop {
public static void main(String[] args) {
MyThread4 my=new MyThread4();
Thread t=new Thread(my);
t.start();//启动线程
//主线程中的循环
for(int i=0;i<5;i++){
if(i==2){
t.stop(); //已过时,不建议使用
}
System.out.println(Thread.currentThread().getName()+"--->"+i);
} }
}

暂停线程执行sleep_yield_join_stop

总结

1.sleep

不会释放锁,Sleep时别的线程也不可以访问锁定对象。

2.yield:

让出CPU的使用权,从运行态直接进入就绪态。让CPU重新挑选哪一个线程进入运行状态。

3.join:

当某个线程等待另一个线程执行结束后,才继续执行时,使调用该方法的线程在此之前执行完毕,也就是等待调用该方法的线程执行完毕后再往下继续执行