【Java基础:线程】使用isAlive()和join()方法

Java基础:线程

线程有多种状态,下面是一般描述:

线程状态描述
运行(running)只要活得CPU时间就准备运行
挂起(suspended)临时停止线程的活动
恢复(resumed)允许线程从停止处恢复执行
阻塞(blocked)当等待资源时,线程会被阻塞

在任何时候,都可以终止线程,这会立即停止线程的执行。线程一旦终止,就不在恢复

创建线程

创建线程有两种方式

  1. 实现Runnable接口
  2. 扩展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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值