Java Thread join() 的用法
2015-06-16 10:30
411 查看
Java Thread中, join() 方法主要是让调用改方法的thread完成run方法里面的东西后, 在执行join()方法后面的代码。示例:
Java代码
class ThreadTesterA implements Runnable {
private int counter;
@Override
public void run() {
while (counter <= 10) {
System.out.print("Counter = " + counter + " ");
counter++;
}
System.out.println();
}
}
class ThreadTesterB implements Runnable {
private int i;
@Override
public void run() {
while (i <= 10) {
System.out.print("i = " + i + " ");
i++;
}
System.out.println();
}
}
public class ThreadTester {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ThreadTesterA());
Thread t2 = new Thread(new ThreadTesterB());
t1.start();
t1.join(); // wait t1 to be finished
t2.start();
t2.join(); // in this program, this may be removed
}
}
如果去掉t1.join()这个语句过后, 输出的书序是乱的, 加上这个语句过后, 就会按照顺序输出, 从某种意义上说实现了同步。
转自:http://auguslee.iteye.com/blog/1292203
Java代码
class ThreadTesterA implements Runnable {
private int counter;
@Override
public void run() {
while (counter <= 10) {
System.out.print("Counter = " + counter + " ");
counter++;
}
System.out.println();
}
}
class ThreadTesterB implements Runnable {
private int i;
@Override
public void run() {
while (i <= 10) {
System.out.print("i = " + i + " ");
i++;
}
System.out.println();
}
}
public class ThreadTester {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ThreadTesterA());
Thread t2 = new Thread(new ThreadTesterB());
t1.start();
t1.join(); // wait t1 to be finished
t2.start();
t2.join(); // in this program, this may be removed
}
}
如果去掉t1.join()这个语句过后, 输出的书序是乱的, 加上这个语句过后, 就会按照顺序输出, 从某种意义上说实现了同步。
转自:http://auguslee.iteye.com/blog/1292203
相关文章推荐
- Eclipse解决js报错
- Java并发编程笔记 使用阻塞队列实现生产者-消费者模型
- Java中String类的方法及说明,示例。
- java.lang.IllegalArgumentException: View not attached to window manager when dismissing dialog
- 在Eclipse中使用JUnit4进行单元测试(中级篇)
- eclipse提示:Syntax error on tokens, delete these tokens怎么解决
- android 开发环境搭建 eclipse支持,解决dl-ssl.google.com资源下载不动问题
- Java去除掉HTML里面所有标签的两种方法——开源jar包和自己写正则表达式
- 【j2ee spring】34、巴巴运动网的产品类别管理
- Java 环境配置
- java将二进制字符串转成int类型数据
- java中访问权限总结
- Java设计模式——Chain of Responsibility(责任链)模式
- Struts 2 – Development mode example
- 关于java ==与 equals.()的问题研究(转)
- java 接口可以多继承
- [java]生成带logo图片的二维码、以及二维码解码
- Java Date, Calendar and Time API - Tutorial
- Spring 学习笔记
- myEclipse中引入各类js文件时验证错误解决办法