java睡眠的线程的时间如何唤醒或动态改变

java睡眠的线程的时间如何唤醒或动态改变,第1张

可以使用sleep()方法

sleep()方法拥有一个参数,誉返它控制睡眠的长短,以毫秒计算。sleep()方法会抛出InterruptedException,纤码所以一定在try-catch块里面使用它。

示例代码如下庆竖饥:

public class A implements Runnable{int i = 0public static void main(String[] args){A a1 = new A() A a2 = new A() a1.run() a2.run() } public void run(){while(++i <= 100){System.out.println(i) try{Thread.sleep(50) }catch(Exception e){e.printStackTrace() }}}}

调姿誉用wait方法使线程进入等待状态的才调用notify or no ti f yAll 如果调扰消用的是线程本身的方法迹李段 sleep 则 应该调用 interrupt方法进行唤醒。

在java中,开启一个多线程是很简单的,只需要new一个runnable就可以了,但是要停止一个线程,却不能简单的使用Thread.stop()方法。

首先来说说java中的中断机制,Java

中断机制是一种协作机制,也就是说通过中断并不能直接终止另一个线程,而需要被中断的线程自己处理中断。当调用interrupt()方法的时候,只是设

置了要中断线程的中断状态,而此时被中断的线程的可以通过isInterrupted()或者是interrupted()方法判断当前线程的中断状态是

否标志为中断。我们可以从interrupt()方法来看:

public void interrupt() {

if (this != Thread.currentThread())

checkAccess()

synchronized (blockerLock) {

Interruptible b = blocker

if (b != null) {

interrupt0() // Just to set the interrupt flag

b.interrupt()

return

}

}

interrupt0()

}

从这个方法中我们悔携可以看到,最直接的调用时interrupt0()这个方法,而这个方法仅仅是设置了线程中断状态。

我们再看看isInterrupted()方法:

public boolean isInterrupted() {

return isInterrupted(false)

}

/**

* Tests if some Thread has been interrupted. The interrupted state

* is reset or not based on the value of ClearInterrupted that is

* passed.

*/

private native boolean isInterrupted(boolean ClearInterrupted)

从这个方法中,我们可以猜测到,isInterrupted()方法仅仅是检查了当前线程的中断状态,但是不会清除这个状态。

我们再来看看静态方法interrupted()

public static boolean interrupted() {

return currentThread().isInterrupted(true)

}

这个方法同样是检测当前线程的中断状态,但是这个方法会产生一个副作用,就是会清碧歼伏除当前线程的中断状态。

Thread.interrupt() VS Thread.stop()

这两个方法最大的区别在于:interrupt()方法是设置线程的中断状态,让用户自己选择时间地点去结束线程;而stop()方法会在代码的运行处直接抛出一个ThreadDeath错误,这是一个java.lang.Error的子类。所以直接使用stop()方法就有可能造成对象的不一致性。

调用Thread.sleep()方法的时候,如果当前线程处于中断那状态,那么sleep()方法不会执行,同时会清除掉该状态,并且抛出interruptedException异常。

改棚中断的使用demo:

package com.app.basic

public class InterruptTest {

public static void main(String[] args) {

Runnable runnable1 = new Runnable() {

@Override

public void run() {

for (int i = 0i <10i++) {

System.out.println(i)

if (Thread.currentThread().isInterrupted()) {

System.out.println("aa")

break

}

try {

Thread.sleep(1000)

} catch (InterruptedException e) {

e.printStackTrace()

//sleep方法抛出这个异常之后会清除中断状态,所以需要重新设置中断状态

Thread.currentThread().interrupt()

}

}

}

}

final Thread t1 = new Thread(runnable1)

Runnable runnable2 = new Runnable() {

@Override

public void run() {

try {

Thread.sleep(3000)

t1.interrupt()

} catch (InterruptedException e) {

e.printStackTrace()

}

}

}

Thread t2 = new Thread(runnable2)

t1.start()

t2.start()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12461646.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存