线程的举例理解

来源:互联网 发布:快更视频软件 编辑:程序博客网 时间:2024/05/16 18:09

public class SimpleThreds {

// 显示当前线程的名称和消息
static void threadMessage(String message) {
String threadNameString = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadNameString, message);
}


private static class MessageLoop implements Runnable {


@Override
public void run() {
// TODO Auto-generated method stub
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++) {
Thread.sleep(4000);// 暂停4秒
threadMessage(importantInfo[i]);// 打印消息显示
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}


public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
long patience = 1000 * 60 * 60;// 设置默认的线程执行时间
// 如果给了命令行参数,则用命令行参数计算线程时间
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;


} catch (NumberFormatException e) {
System.err.println("参数必须是一个整数。");
System.exit(1);
}
}
threadMessage("Starting MessageLoop thread");// 提示main线程起动
long startTime = System.currentTimeMillis();// 获得当时时间点,用来判断子线程启动的时间
Thread t = new Thread(new MessageLoop());// 创建子线程0
t.start();// 线程0起动,在此:main线程和子线程0同时运行
threadMessage("Waiting for MessageLoop thread to finish");// 主线程等等子线程0的完成
while (t.isAlive()) {// 子线程0是否还是活动的,若是


threadMessage("Still waiting...");// main主线程显示:依然在等待
t.join(1000);// 给子线程1秒钟去完成,即1秒后,主线程与子线程同步
if ((System.currentTimeMillis() - startTime) > patience
&& t.isAlive()) {// 已经1秒了,判断子线程运行的时间是否到了设定时间,若没到继续main线程的while循环,若到了且子线程0仍然活着,则:
threadMessage("Tired of waiting!");// 主线程显示:等累了
t.interrupt();// main主线程让子线程终止
t.join();// main线程一直等待子线程0的终止
}
}
threadMessage("Finally!");// main线程完成
}


}







0 0
原创粉丝点击