首页 > 代码库 > JAVA多线程---wait() & join()

JAVA多线程---wait() & join()

题外话:

interrupt()方法  并不能中断一个正常运行的线程!!!

class myThread extends Thread{
    @Override
    public void run(){
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }
}
public class waitTest {

    public static void main(String[] args) throws Exception{
        Thread t =new myThread();
        t.start();
        t.interrupt();
        System.out.println("mark");
    }

}

 

输出:

mark

......

i=999


 

join()方法 

具体用法http://www.cnblogs.com/luyu1993/p/7017927.html

这里看下它的源码

public final synchronized void join(long millis) 
    throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
        wait(0);
        }
    } else {
        while (isAlive()) {
        long delay = millis - now;
        if (delay <= 0) {
            break;
        }
        wait(delay);
        now = System.currentTimeMillis() - base;
        }
    }
    }

  

join()内部调用的是wait()  注意 在调用wait()之前,线程必须获得该对象的锁,因此只能在同步方法/同步代码块中调用wait()方法。可以看见join()方法是synchronized的 所以没问题

看下面这段代码

 1 class myThread extends Thread{
 2     @Override
 3     public void run(){
 4         for (int i = 0; i < 1000; i++) {
 5             System.out.println(i);
 6         }
 7     }
 8 }
 9 public class waitTest {
10 
11     public static void main(String[] args) throws Exception{
12         Thread t =new myThread();
13         t.start();
14         Thread.currentThread().wait();
15         System.out.println("mark");
16     }
17 
18 }

此时程序会报错  不在同步方法/同步代码块 中调用wait()方法的错误!!!

技术分享

 

JAVA多线程---wait() & join()