DemoJoin

package java_learning;
//using join() to wait thread to finish 

class NewThread implements Runnable{
	String m_name;
	Thread m_t;
	NewThread(String threadname){
		m_name = threadname;
		m_t = new Thread(this, m_name);
		System.out.println("New thread:"+m_name);
		m_t.start(); // Start the thread
	}
	
	@Override
	public void run() {
		// TODO 自动生成的方法存根
		try {
            for(int i = 5; i > 0; i--) {
               System.out.println(m_name + ": " + i);
               Thread.sleep(1000);//让其他线程有时间运行
            }
        } catch (InterruptedException e) {
            System.out.println(m_name + " interrupted.");
        }
        System.out.println(m_name + " exiting.");
    }
}

public class DemoJoin{
	public static void main(String[]args){
		NewThread ob1 = new NewThread("thread1");
		NewThread ob2 = new NewThread("thread2");
		NewThread ob3 = new NewThread("thread3");
		System.out.println("Thread1 is alive:"+ob1.m_t.isAlive());
		System.out.println("thread1 is alive:"+ob2.m_t.isAlive());
		System.out.println("thread1 is alive:"+ob3.m_t.isAlive());
		 // wait for threads to finish,希望主线程最后结束
		//join()方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。
		//join()的附加形式允许给等待指定线程结束定义一个最大时间。
		//运用join()以确保主线程最后结束。
		try {
            System.out.println("Waiting for threads to finish.");
            ob1.m_t.join();//等待ob1线程结束
            ob2.m_t.join();//等待ob2线程结束
            ob3.m_t.join();//等待ob3线程结束
        } catch (InterruptedException e) {
            System.out.println("Main thread Interrupted");
        }
       
		System.out.println("Thread One is alive: "+ ob1.m_t.isAlive());
        System.out.println("Thread Two is alive: "+ ob2.m_t.isAlive());
        System.out.println("Thread Three is alive: "+ ob3.m_t.isAlive());
        System.out.println("Main thread exiting.");
		
	}
}

运行结果:
New thread:thread1
New thread:thread2
thread1: 5
New thread:thread3
thread2: 5
Thread1 is alive:true
thread1 is alive:true
thread1 is alive:true
Waiting for threads to finish.
thread3: 5
thread1: 4
thread3: 4
thread2: 4
thread1: 3
thread3: 3
thread2: 3
thread1: 2
thread3: 2
thread2: 2
thread1: 1
thread3: 1
thread2: 1
thread1 exiting.
thread3 exiting.
thread2 exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值