Java创建多线程

    |     2015年4月13日   |   多线程编程   |     0 条评论   |    1541

到目前为止只用到两条线程:主线程和一个子线程。程序可以按需要创建更多。下面这个例子创建了三个子线程 One、Two、Three。

每个 NewThread 在构造函数里 start(),从 5 数到 1,每次睡 1 秒。主线程用 sleep(10000) 睡十秒,确保自己最后结束。

线程 做什么 等待策略
One / Two / Three 各自倒数并 sleep(1000) 约 5 秒结束
main 启动三个子线程 sleep(10000) 保底最后退出

一、三个子线程的代码

class NewThread implements Runnable {
    String name;
    Thread t;
    NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start();
    }
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println(name + ": " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println(name + "Interrupted");
        }
        System.out.println(name + " exiting.");
    }
}

class MultiThreadDemo {
    public static void main(String args[]) {
        new NewThread("One");
        new NewThread("Two");
        new NewThread("Three");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Main thread Interrupted");
        }
        System.out.println("Main thread exiting.");
    }
}

二、输出说明

启动后三个子线程共享 CPU,打印交错出现是正常的(谁先谁后取决于调度):

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
...
One exiting.
Two exiting.
Three exiting.
Main thread exiting.

用固定 10 秒 sleep 只是权宜之计;子线程变多或变慢时可能不够。更稳的做法是对每条线程 join()。

一句话总结:多条子线程 new 完立刻 start,它们会交错抢 CPU;主线程要用足够长的 sleep 或 join,保证自己最后一个退出。

转载请注明来源:Java创建多线程
本文链接地址:https://ai.zhousir.top/?p=213
回复 取消