文档

Java™ 教程
隐藏目录
SimpleThreads示例
路径:基本Java类
课程:并发
章节:线程对象

SimpleThreads示例

以下示例将本节中的一些概念汇集在一起。SimpleThreads由两个线程组成。第一个线程是每个Java应用程序都有的主线程。主线程从Runnable对象MessageLoop创建一个新线程,并等待其完成。如果MessageLoop线程花费的时间过长,主线程会中断它。

MessageLoop线程打印一系列消息。如果在打印所有消息之前被中断,MessageLoop线程将打印一条消息并退出。

public class SimpleThreads {

    // 显示一条消息,前面带上
    // 当前线程的名称
    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[] = {
                "马吃燕麦",
                "母鹿吃燕麦",
                "小羊吃常春藤",
                "小孩也会吃常春藤"
            };
            try {
                for (int i = 0;
                     i < importantInfo.length;
                     i++) {
                    // 暂停4秒
                    Thread.sleep(4000);
                    // 打印一条消息
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("我还没完成呢!");
            }
        }
    }

    public static void main(String args[])
        throws InterruptedException {

        // 在中断MessageLoop
        // 线程之前延迟的毫秒数(默认为一小时)。
        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("启动MessageLoop线程");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("等待MessageLoop线程完成");
        // 循环直到MessageLoop
        // 线程退出
        while (t.isAlive()) {
            threadMessage("仍在等待...");
            // 最多等待1秒
            // 直到MessageLoop线程完成。
            t.join(1000);
            if (((System.currentTimeMillis() - startTime) > patience)
                  && t.isAlive()) {
                threadMessage("等得太久了!");
                t.interrupt();
                // 现在不应该再等了
                // -- 无限等待
                t.join();
            }
        }
        threadMessage("终于完成了!");
    }
}

上一页: 连接
下一页: 同步