设为首页 加入收藏

TOP

Java主线程等待子线程、线程池 (一)
2014-11-24 10:24:25 】 浏览:10855
Tags:Java 线程 等待

print public class TestThread extends Thread
{
public void run()
{
System.out.println(this.getName() + "子线程开始");
try
{
// 子线程休眠五秒
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(this.getName() + "子线程结束");
}
}

public class TestThread extends Thread
{
public void run()
{
System.out.println(this.getName() + "子线程开始");
try
{
// 子线程休眠五秒
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(this.getName() + "子线程结束");
}
}
首先是一个线程,它执行完成需要5秒。

1、主线程等待一个子线程

[java] public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

Thread thread = new TestThread();
thread.start();

long end = System.currentTimeMillis();
System.out.println("子线程执行时长:" + (end - start));
}
}

public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

Thread thread = new TestThread();
thread.start();

long end = System.currentTimeMillis();
System.out.println("子线程执行时长:" + (end - start));
}
}


在主线程中,需要等待子线程执行完成。但是执行上面的main发现并不是想要的结果:

子线程执行时长:0

Thread-0子线程开始

Thread-0子线程结束

很明显主线程和子线程是并发执行的,主线程并没有等待。

对于只有一个子线程,如果主线程需要等待子线程执行完成,再继续向下执行,可以使用Thread的join()方法。join()方法会阻塞主线程继续向下执行。

[java] public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

Thread thread = new TestThread();
thread.start();

try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}

long end = System.currentTimeMillis();
System.out.println("子线程执行时长:" + (end - start));
}
}

public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

Thread thread = new TestThread();
thread.start();

try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}

long end = System.currentTimeMillis();
System.out.println("子线程执行时长:" + (end - start));
}
}


执行结果:

Thread-0子线程开始

Thread-0子线程结束

子线程执行时长:5000

注意:join()要在start()方法之后调用。

2、主线程等待多个子线程

比如主线程需要等待5个子线程。这5个线程之间是并发执行。

[java] public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

for(int i = 0; i < 5; i++)
{
Thread thread = new TestThread();
thread.start();

try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}

long end = System.currentTimeMillis();
System.out.println("子线程执行时长:" + (end - start));
}
}

public class Main
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();

for(int i = 0; i < 5; i++)
{
Thread thread = new TestThread();
thread.start();

try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTra

首页 上一页 1 2 3 4 下一页 尾页 1/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇eclipse/myeclipse使用技巧 下一篇Java建议:推荐使用String直接量..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目