Java多线程学习与总结(Join)

join()方法的用法:

join()是主线程 等待子线程的终止。也就是在子线程调用了 join() 方法后面的代码,只有等到子线程结束了才能执行。

例子如下:

Java代码 复制代码 收藏代码
  1. public class Test implements Runnable {
  2. private static int a = 0;
  3. public void run() {
  4. for(int i=0;i<10;i++)
  5. {
  6. a = a + i;
  7. }
  8. }
  9. /**
  10. * @param args
  11. * @throws InterruptedException
  12. */
  13. public static void main(String[] args) throws InterruptedException {
  14. Thread t1 = new Thread(new Test());
  15. t1.start();
  16. //Thread.sleep(10);
  17. //t1.join();
  18. System.out.print(a);
  19. }
  20. }
public class Test implements Runnable {

	private static int a = 0;
	
	public void run() {
		
		for(int i=0;i<10;i++)
		{
			a = a + i;
		}
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(new Test());
		t1.start();
		//Thread.sleep(10);
		//t1.join();
		System.out.print(a);
		
	}
}

上面程序最后的输出结果是0,就是当子线程还没有开始执行时,主线程已经结束了。

Java代码 复制代码 收藏代码
  1. public class Test implements Runnable {
  2. private static int a = 0;
  3. public void run() {
  4. for(int i=0;i<10;i++)
  5. {
  6. a = a + i;
  7. }
  8. }
  9. /**
  10. * @param args
  11. * @throws InterruptedException
  12. */
  13. public static void main(String[] args) throws InterruptedException {
  14. Thread t1 = new Thread(new Test());
  15. t1.start();
  16. //Thread.sleep(10);
  17. t1.join();
  18. System.out.print(a);
  19. }
  20. }
public class Test implements Runnable {

	private static int a = 0;
	
	public void run() {
		
		for(int i=0;i<10;i++)
		{
			a = a + i;
		}
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(new Test());
		t1.start();
		//Thread.sleep(10); 
                t1.join();
		System.out.print(a);
		
	}
}

上面程序的执行结果是45,就是当主线程运行到t1.join()时,先执行t1,执行完毕后在执行主线程余下的代码!

总结:join()方法的主要功能就是保证调用join方法的子线程先执行完毕再执行主线程余下的代码!

猜你喜欢

转载自blog.csdn.net/Gavinlib/article/details/8732025