您的位置:首页 > 编程语言 > Java开发

java多线程(二) sleep(),yield(),wait(), interrupt()方法

2014-05-11 13:37 465 查看
Thread对象调用start方法后,线程处于可运行状态,等待cpu分配给该线程。

sleep(),yield()方法都可以让正在运行的线程,放弃cpu

sleep(),在睡眠指定的时间后,自动变为可运行状态

yield(),让当前运行线程回到可运行性状态,使得有相同优先级的线程有机会执行。

 wait( ): 类似sleep( ), 不同的是,wait( )会先释放锁住的对象,然后再执行等待的动作。注意,这个函数属于Object类。另外,由于wait( )所等待的对象必须先锁住,因此,它只能用在同步化程序段或者同步化方法内,否则,会抛出异常IllegalMonitorStateException.

在看一个网上找到的例子

package lock;
public class Pool {
public Connection get(){
synchronized (this) {
if(free>0){
free--;
}else{
this.wait();
}
return cacheConnection.poll();

}
}
public void close(Connection conn){
synchronized (this) {
free++;
cacheConnection.offer(conn);
this.notifyAll();
}
}
}

interrupt()也是线程调用的

这里参考网上别人写的一段代码

class ATask implements Runnable{

private double d = 0.0;

public void run() {
//死循环执行打印"I am running!" 和做消耗时间的浮点计算
try {
while (true) {
System.out.println("I am running!");

for (int i = 0; i < 900000; i++) {
d =  d + (Math.PI + Math.E) / d;
}
//休眠一断时间,中断时会抛出InterruptedException
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("ATask.run() interrupted!");
}
}
}
在这儿需要捕获InterruptedException异常,就是线程要去捕获中断异常

也可以去检查是否有中断

class ATask implements Runnable{

private double d = 0.0;

public void run() {

//检查程序是否发生中断
while (!Thread.interrupted()) {
System.out.println("I am running!");

for (int i = 0; i < 900000; i++) {
d = d + (Math.PI + Math.E) / d;
}
}

System.out.println("ATask.run() interrupted!");
}
}


可以结合两个一起用

class ATask implements Runnable{

private double d = 0.0;

public void run() {

try {
//检查程序是否发生中断
while (!Thread.interrupted()) {
System.out.println("I am running!");
//point1 before sleep
Thread.sleep(20);
//point2 after sleep
System.out.println("Calculating");
for (int i = 0; i < 900000; i++) {
d = d + (Math.PI + Math.E) / d;
}
}

} catch (InterruptedException e) {
System.out.println("Exiting by Exception");
}

System.out.println("ATask.run() interrupted!");
}
}


主函数为

public class InterruptTaskTest {

public static void main(String[] args) throws Exception{
//将任务交给一个线程执行
Thread t = new Thread(new ATask());
t.start();

//运行一断时间中断线程
Thread.sleep(100);
System.out.println("****************************");
System.out.println("Interrupted Thread!");
System.out.println("****************************");
t.interrupt();
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  wait sleep yield interrupt