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类,无法继承其他类,如果第二种还可以继承其他类

    */

    }

  • 相关阅读:
    另类多线程生产者与消费者模式
    redis.conf配置详细翻译解析
    数据库优化之索引使用简介
    Comparable和Comparator的区别
    spring中用到哪些设计模式
    JVM之几种垃圾收集器简单介绍
    angular.extend()和 angular.copy()的区别
    ThreadLocal是什么?保证线程安全
    excel文件怎么使用php进行处理
    ubuntu 安装ssh 服务
  • 原文地址:https://www.cnblogs.com/NuoChong/p/12268542.html
Copyright © 2011-2022 走看看