线程:方法join的使用

  方法join()的作用是等待线程对象销毁。

  方法join()的作用是所属的线程对象x正常执行run()方法中的任务, 而使当前线程z进行无限期的阻塞,等待线程x销毁后再继续执行线程z后面的代码。

public class MyThread extends Thread{
	
	@Override
	public void run(){
		try {
			int secondValue = (int)(Math.random() * 10000);
			System.out.println(secondValue);
			Thread.sleep(secondValue);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


public class Test {
	public static void main(String[] args){
		try {
			MyThread threadTest = new MyThread();
			threadTest.start();
			threadTest.join();
			System.out.println("我想当threadTest对象执行完毕后我再执行");
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

方法join(long)与sleep(long)的区别

   方法join(long)的功能内部是使用wait(long)方法来实现的, 所以join(long)方法具有释放锁的特点。

  

发布了557 篇原创文章 · 获赞 40 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/103407917