0
点赞
收藏
分享

微信扫一扫

5.线程常见方法

扬帆远航_df7c 2022-03-16 阅读 43

1.join方法:当一个线程调用了join方法,这个线程就会先被执行,它执行结束以后才可以去执行其余的线程

注意:必须先start(),再join()才有效

public class MyThread extends Thread{
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i=1;i<=10;i++){
            System.out.println(this.getName()+"---->"+i);
        }
    }
}

class TestThread{
    //这是main方法
    public static void main(String[] args) throws InterruptedException {
        for (int i=1;i<=20;i++){
            if (i==6){
                //创建子线程
                MyThread mt = new MyThread("子线程");
                mt.start();
                mt.join();//半路杀出陈咬金
            }
            System.out.println("main----->" + i);
        }
    }
}

2.sleep:人为的制造阻塞事件

public static void main(String[] args) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Hello World");
    }

案例:完成秒表功能

public static void main(String[] args) {
        while(true){
            //1.获取当前时间:
            Date date = new Date();
            //System.out.println(date);
            //2.定义一个时间格式
            DateFormat df=new SimpleDateFormat("HH:mm:ss");
            //3.按照上面定义的格式将Date类型转为指定格式的字符串
            System.out.println(df.format(date));
            //4.启用线程睡眠间隔1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

3.setDaemon:设置伴随线程

将子线程设置为主线程的伴随线程,主线程停止的时候,子线程也不要继续执行了

案例:皇上(主线程)-->驾崩-->妃子陪葬(子线程)

public class MyThread extends Thread{

    @Override
    public void run() {
        for (int i=1;i<=1000;i++){
            System.out.println("子线程---->"+i);
        }
    }
}

class TestThread{
    //这是main方法
    public static void main(String[] args) throws InterruptedException {
        MyThread mt = new MyThread();
        mt.setDaemon(true);//设置伴随线程 注意:先设置,再启动
        mt.start();
        for (int i=1;i<=10;i++){
            System.out.println("main----->" + i);
        }
    }
}

4.stop方法

public static void main(String[] args) {
        for (int i=2;i<=100;i++){
            if (i==6){
                Thread.currentThread().stop();//过期方法,不建议使用
            }
            System.out.println(i);
        }
    }
举报

相关推荐

0 条评论