Joins

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleepjoin is dependent on the OS for timing, so you should not assume thatjoin will wait exactly as long as you specify.

Like sleepjoin responds to an interrupt by exiting with an InterruptedException.

译文:

连接

连接方法允许一个线程等待另外一个线程执行完毕。如果t是正在执行的一个thread对象。

t.join();

引起当前线程停止执行知道t这个线程终止。重载join方法允许程序员指定一段等待时间。然而,同sleep方法一样,join方法也是依赖于系统时间的,因此不要认为join等待的时间会和你指定的一模一样。同sleep方法一样,join返回一个中断如果捕获到一个interruptedException异常。

The SimpleThreads Example

The following example brings together some of the concepts of this section. SimpleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object,MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it.

The MessageLoop thread prints out a series of messages. If interrupted before it has printed all its messages, theMessageLoop thread prints a message and exits.

public class SimpleThreads {

    // Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName();
System.out.format("%s: %s%n",
threadName,
message);
} private static class MessageLoop
implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
} public static void main(String args[])
throws InterruptedException { // Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default one hour).
long patience = 1000 * 60 * 60; // If command line argument
// present, gives patience
// in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
} threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start(); threadMessage("Waiting for MessageLoop thread to finish");
// loop until MessageLoop
// thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
}
译文:
简单的线程实例
下面的这个实例包括了这一节介绍的内容。SimpleThreads包含了两个线程。第一个是每个java程序都有的主线程。主线程中创建了一个新的messageloop线程,主线程需要一直等到它执行完。如果MessageLoop线程占用了太长的时间,那么主线程就会抛出interruptedException中断它。
MessageLoop线程打印一串信息,如果中断发生在这个线程执行打印操作完毕前,那么就会打印中断信息,并且退出这个线程。
 public class SimpleThreads {

     // Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName();
System.out.format("%s: %s%n",
threadName,
message);
} private static class MessageLoop
implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
} public static void main(String args[])
throws InterruptedException { // Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default one hour).
long patience = 1000 * 60 * 60; // If command line argument
// present, gives patience
// in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
} threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start(); threadMessage("Waiting for MessageLoop thread to finish");
// loop until MessageLoop
// thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
}

养眼是必须滴^^.

 

【翻译六】java-连接和实例的更多相关文章

  1. 功能完善的Java连接池调用实例

    /** * Title: ConnectPool.java * Description: 连接池管理器 * Copyright: Copyright © 2002/12/25 * Company: * ...

  2. java连接mysql8.0.28数据库实例

    首先说明,由于是8版本的数据库,所以配置类的写法上与5版本的有所区别,需要注意,同时用idea或eclipse时需要导入jar包,jar包的下载链接: https://dev.mysql.com/ge ...

  3. JAVA上百实例源码以及开源项目

    简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级.中级.高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情.执着,对IT的憧憬. ...

  4. JAVA上百实例源码网站

    JAVA源码包1JAVA源码包2JAVA源码包3JAVA源码包4 JAVA开源包1 JAVA开源包2 JAVA开源包3 JAVA开源包4 JAVA开源包5 JAVA开源包6 JAVA开源包7 JAVA ...

  5. Java连接远程Redis

    redis-server &  //后台启动redis redis-cli //使用redis   打开redis.conf文件在NETWORK部分有说明   /usr/local/src   ...

  6. java连接mysql数据库详细步骤解析

    java连接mysql数据库详细步骤解析      第一步:下载一个JDBC驱动包,例如我用的是:mysql-connector-java-5.1.17-bin.jar      第二步:导入下载的J ...

  7. java连接mysql步骤

    转自:http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html JDBC连接mysql数据库   •创建一个以JDBC连接数据库的程 ...

  8. java 连接 MySQL

    java 连接 MySQL 1.准备工作 需要下载的工具: MySQL:http://www.mysql.com/downloads/ MySQL的可视化工具SQLyog:https://www.we ...

  9. java连接sql server2000/2005

    接触Java或者JSP,难免会使用到数据库SQL Server 2000/2005(我使用2005标准版[9.0.3054]测试),经过自己的搜索和研究,使用JDBC连接SQL Server成功,特此 ...

  10. Java 连接MongoDB

    1.驱动 通过java连接MongoDB需要一个java版的驱动 下载地址:http://mongodb.github.io/mongo-java-driver/ 2.连接MongoDB 通过 com ...

随机推荐

  1. HackerRank training-the-army

    Description 有 \(n\) 个技能,每次可以通过一个巫师,将一个技能转化成另一个技能,问最有最多有多少不同的技能. Sol 网络流. 先说说我一开始非常 naive 的建图,将技能拆点,中 ...

  2. HDU 1024 max sum plus

    A - Max Sum Plus Plus Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I6 ...

  3. MyEclipse 15 集成SVN

    一.在线更新 地址:http://subclipse.tigris.org/update_1.8.x 二.手动安装

  4. 解决ckeditor中文路径无法下载,无法显示图片问题

    使用ckfinder上传的文件如果是中文路径,下载的时候会找不到 假如使用tomcat服务器,找到tomcat目录>conf文件夹的server.xml>用查找找到Connector这个 ...

  5. python——有限状态机

    前言 使用Python,大部分时间花在了处理文本上.在处理文本的时候,如果对有限状态机有所了解的话,处理起来会更加得心应手.可以把文本看成一个流,然后有一个机器对这个流进行操作.这个机器有状态,不同的 ...

  6. TCP三次握手原理详解

    TCP/IP协议不是TCP和IP这两个协议的合称,而是指因特网整个TCP/IP协议族. 从协议分层模型方面来讲,TCP/IP由四个层次组成:网络接口层.网络层.传输层.应用层. TCP协议:即传输控制 ...

  7. wxpython 基本的控件 (按钮)

    使用按钮工作 在wxPython 中有很多不同类型的按钮.这一节,我们将讨论文本按钮.位图按钮.开关按钮(toggle buttons )和通用(generic )按钮. 如何生成一个按钮? 在第一部 ...

  8. 推荐一篇 OAuth 2.0 必读文章

    http://www.cnblogs.com/artech/p/oauth-03.html 共计有3篇相关内容,请仔细阅读! 再说一下我用box api 开发时的问题,在 box 程序登记页面: 对于 ...

  9. redis 中文字符显示

    2015年5月20日 09:57:01 星期三 方法一: redis-cli -h --raw 方法二: linux 终端: echo -e "\xe7\xa5\x9e\xe6\xa3\x8 ...

  10. ACM/ICPC 之 最短路-Floyd+SPFA(BFS)+DP(ZOJ1232)

    这是一道非常好的题目,融合了很多知识点. ZOJ1232-Adventrue of Super Mario 这一题折磨我挺长时间的,不过最后做出来非常开心啊,哇咔咔咔 题意就不累述了,注释有写,难点在 ...