在某些情况下,主线程创建并启动了子线程,如果子线程中需要进行大量的耗时运算,主线程往往将早于子线程结束之前结束,如果主线程想等待子线程执行完毕后,获得子线程中的处理完的某个数据,就要用到join方法了,方法join()的作用是等待线程对象呗销毁。
public class AccountingSync implements Runnable
{
//共享资源(临界资源)
static int i=0;
/**
* synchronized 修饰实例方法
*/
public void increase(){
synchronized(this)
{
i++;
}
}
@Override
public void run() {
for(int j=0;j<1000000;j++){
increase();
}
}
public static void main(String[] args) throws InterruptedException {
AccountingSync instance=new AccountingSync();
Thread t1=new Thread(instance);
Thread t2=new Thread(instance);
t1.start();
t2.start();
t1.join(1);//主线程要等待t1线程执行完毕
t2.join(100);
System.out.println(i);
}
}
/**
* 输出结果:
* 2000000
*/
join底层是wait方法,所以它是会释放对象锁的,而sleep在同步的方法中是不释放对象锁的,只有同步方法执行完毕,其他线程才可以执行。
(1).myThread.join();//不指定当前线程wait的时间,这会导致当前线程一直阻塞至myThread执行完毕
(2).myThread.join
(long time);//指定当前线程wait时间,这回导致当前线程一直阻塞time毫秒或者myThread执行完毕
void join(long millis, int nanos)
等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。
网友评论