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. caffe学习系列(3):数据层介绍

    一个模型由多个层构成,如Data,conv,pool等.其中数据层是模型的最底层,是模型的入口. 提供数据的输入,也提供数据从Blobs转换成别的格式进行保存输出还包括数据的预处理(如减去 均值, 放 ...

  2. SNMP报文抓取与分析(二)

    SNMP报文抓取与分析(二) SNMP报文抓取与分析(二) 1.SNMP报文表示简介 基本编码规则BER 标识域Tag表示 长度域length表示 2.SNMP报文详细分析(以一个get-respon ...

  3. postgresql数据库实用操作

    查模型的列名: select column_name from information_schema.columns  where table_name= 'your_table'; 应用: 1. 给 ...

  4. JustMock Lite (Free Mocking Framework For .net)

    通过 Nuget 安装 2.   官网下载(官网不行点这里) 3.   帮助文档 商业版和免费版区别概览 MockingContainer 测试类准备:一般来说也是业务类 public class C ...

  5. FreeRTOS--删除任务

    FreeRTOS学习笔记——任务删除 vTaskDelete() API - liyan728的专栏 - 博客频道 - CSDN.NET http://blog.csdn.net/liyan728/a ...

  6. MySQL ODBC for Linux

    参考自http://blog.csdn.net/allens_zhou/article/details/8575400 centos7 64bit [IP:192.168.0.100] yum ins ...

  7. appium + python 环境搭建

    所需:JDK.Android SDK.Appium服务程序.Appium客户端程序 1. 安装最新的JDK,并配置环境变量. JAVA_HOME=C:\Program Files (x86)\Java ...

  8. spinlock原理

    [参考] http://www.searchtb.com/2011/06/spinlock%E5%89%96%E6%9E%90%E4%B8%8E%E6%94%B9%E8%BF%9B.html

  9. android打电话的小程序

    主要使用了Intent以及uses-permission标签. call.rar 下载后直接导入项目

  10. JAVA手记 JAVA入门(安装+Dos下运行)

    JAVA入门特供= =,今天设置环境变量后用dos运行的时候发现出现“找不到或无法加载主类”,索性查了些资料重新看了看JAVA入门的部分. 声明:我的笔记本暂时用的是Win10系统,Windows其他 ...