Java基础:线程
线程有多种状态,下面是一般描述:
| 线程状态 | 描述 | 
|---|---|
| 运行(running) | 只要活得CPU时间就准备运行 | 
| 挂起(suspended) | 临时停止线程的活动 | 
| 恢复(resumed) | 允许线程从停止处恢复执行 | 
| 阻塞(blocked) | 当等待资源时,线程会被阻塞 | 
创建线程
创建线程有两种方式
- 实现Runnable接口
 - 扩展thread类本身
 
使用isAlive()和join()方法
因为子线程必须在主线程终止前终止,我们需要知道子线程何时结束
isAlive():如果线程仍然在运行,返回true,否则返回false
 join():调用线程一直等待,直到指定的线程加入(join)其中为止。另一种形式,允许指定希望等待指定线程终止的最长时间。
/*
 * Copyright (c) 2022. Author:brooks   email:myt2000@126.com
 */
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(); // start() 通过调用run() 方法启动线程
    }
    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 DemoJoin {
    public static void main(String[] args) {
        NewThread ob1 = new NewThread("One");
        NewThread ob2 = new NewThread("Two");
        NewThread ob3 = new NewThread("Three");
        System.out.println("Thread One is alive:" + ob1.t.isAlive());
        System.out.println("Thread Two is alive:" + ob2.t.isAlive());
        System.out.println("Thread Three is alive:" + ob3.t.isAlive());
        try {
            System.out.println("Waiting for threads to finish.");
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread Interrupted");
        }
        System.out.println("Thread One is alive:" + ob1.t.isAlive());
        System.out.println("Thread Two is alive:" + ob2.t.isAlive());
        System.out.println("Thread Three is alive:" + ob3.t.isAlive());
        System.out.println("Main thread exiting.");
    }
}
 
输出结果:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Two: 5
One: 5
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
Three: 1
Two: 1
One: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive:false
Thread Two is alive:false
Thread Three is alive:false
Main thread exiting.










