Thread 类的基本用法

目录

一. 线程创建

1.继承Thread类 重写run().

2.通过实现Runnable 来实现创建线程.

3.使用匿名内部类, 来创建 Thread 子类.

4. 使用匿名内部类, 实现Runnable接口.

5. lambda 表达式

二. 线程中断

1. 什么是线程中断?

2.定义标志位

1.自己定义

2.使用标准库自带的标志位

三. 线程等待

四. 线程休眠

五. 获取线程实例


一. 线程创建

1.继承Thread类 重写run().

class MyThread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("thread");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();

        while (true) {
            System.out.println("main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.通过实现Runnable 来实现创建线程.

class MyRunnable implements Runnable {
    @Override
    public void run() {
        while (true) {
            System.out.println("thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Demo2 {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();


        while (true) {
            System.out.println("main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

 这里的话, 就把线程要干的活和线程本身分开了, 使用 runnable 专门来表示 "线程要完成的工作", 把任务提取出来, 就是为了 解耦合 , 上面继承 Thread 的写法就是把线程要完成的工作和线程本身, 耦合在一起了. 而 runnable 这种写法, 只需要把 runnable 传给其他实体就可以了.

3.使用匿名内部类, 来创建 Thread 子类.

// 使用匿名内部类, 来创建 Thread 子类
    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("thread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        
        thread.start();
    }
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

即将秃头的菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值