zoukankan      html  css  js  c++  java
  • java中的join用法

    t1.join();

    在谁里面调用就把谁阻塞

    join()方法的作用,是等待这个线程结束;
    也就是说,t.join()方法 阻塞调用此方法的线程(calling thread)进入 TIMED_WAITING 状态,直到线程t完成,此线程再继续;
    通常用于在main()主线程内,等待其它线程完成再结束main()主线程。

    t1.join在main里面执行的,所以main线程被阻塞了,直到t1线程执行完毕,才执行main函数的线程


    public class lx01 {

    /*
    * 实现多线程的两种方法
    * 1、继承Thread类
    * 2、实现Runnable接口(推荐使用)
    * */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(Thread.currentThread().getName());
    MyThread t1= new MyThread();
    t1.start();

    //System.out.println("isAlive: "+t1.isAlive());

    MyRunnable r = new MyRunnable();
    Thread t2 =new Thread(r);
    System.out.println("isAlive: "+t2.isAlive());//false
    t2.start();
    System.out.println("isAlive: "+t2.isAlive());//true

    for(int i=0;i<10;i++)
    {
    try {
    System.out.println(System.currentTimeMillis()+"-"+i+"--"+Thread.currentThread().getName());
    Thread.sleep(500);
    } catch (InterruptedException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    if(i==6)
    {
    try {
    t1.join();/*

    在谁里面调用就把谁阻塞

    join()方法的作用,是等待这个线程结束;
    也就是说,t.join()方法 阻塞调用此方法的线程(calling thread)进入 TIMED_WAITING 状态,直到线程t完成,此线程再继续;
    通常用于在main()主线程内,等待其它线程完成再结束main()主线程。

    t1.join在main里面执行的,所以main线程被阻塞了,直到t1线程执行完毕,才执行main函线程*/
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    }
    static class MyThread extends Thread //Thread就是继承Runnable
    {
    public void run()
    {
    for(int i=0;i<10;i++)
    {
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {//中断异常
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(System.currentTimeMillis()+"-"+i+"--"+Thread.currentThread().getName());
    }
    }
    }
    //轻耦合,实现Runnable接口的方式启动线程
    static class MyRunnable implements Runnable
    {
    @Override
    public void run() {
    // TODO Auto-generated method stub
    for(int i=0;i<10;i++)
    {
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {//中断异常
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    System.out.println(System.currentTimeMillis()+"-"+i+"--"+Thread.currentThread().getName());
    }
    }
    }

    /*
    * 推荐第二种 方法
    * 第一种已经继承了Thread类,无法继承其他类,如果第二种还可以继承其他类

    */

    }

  • 相关阅读:
    将一个float型转化为内存存储格式的步骤
    判断是否是中文、英文字符串
    打开文件对话框
    线性表之四,受限的线性表,队列
    线性表之三,受限的线性表,栈
    数据结构
    List
    SamplesHashtable
    Exception
    maven指定本地仓库
  • 原文地址:https://www.cnblogs.com/NuoChong/p/12268542.html
Copyright © 2011-2022 走看看