线程的举例理解

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值