你真的会用Thread类嘛?

一、线程创建

线程的创建总的来说有7种方式,我把这几种方式分为以下三大类,其中有带返回值的(继承Thread类创建线程;实现Runnable接口创建线程),也有不带返回值的(实现Callable接口创建线程)。

1.1继承Thread类创建线程

1.继承Thread类创建线程

这种方法创建线程显得太过复杂,一般不推荐

public class ExtendThread {
    public static void main(String[] args) {
        CreadThread thread=new CreadThread("线程1");
        thread.start();
    }
    static class CreadThread extends Thread{
        public CreadThread(String ret) {
            super(ret);
        }
        @Override
        public void run() {
            System.out.println("线程开启!");
            Thread t=currentThread();
            System.out.println(t.getName());
        }
    }
}

1.2实现Runnable接口创建线程

1.创建一个新的类实现Runnable

这种方法创建线程显得太过复杂,一般不推荐

public class Method2 {
    public static void main(String[] args) {
        MyTread MyThread = new MyTread();
        Thread thread = new Thread(MyThread);
        thread.start();
    }
}
class MyTread implements Runnable{

    @Override
    public void run() {
        System.out.println("线程创建成功了!");
    }
}

2.使用匿名类创建线程

这种方式在jdk1.8之前的版本来说也算非常简洁了,但是更推荐下一种创建线程的方法

public class Method3 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程创建成功");
            }
        });
        thread.start();
    }
}

3.使用lambda表达式创建线程(推荐)

这种线程创建的方式应该是目前最简洁的方式,但是要注意,这种方式必须要保证jdk1.8以上!

public class Method5 {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            System.out.println("线程创建成功");
        });
        thread.start();
    }
}

4.匿名方式创建

public class Method4 {
    public static void main(String[] args) {
        Thread thread=new Thread(){
            @Override
            public void run() {
                System.out.println("线程创建成功!");
            }
        };
        thread.start();
    }
}

1.3实现Callable接口创建线程

1.实现Callable接口创建线程

这种带返回值的创建可以有返回值,但是得借助FutureTask,我们还可以对这种方法进行改进,使得代码更加简洁

public class Method6 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable=new MyCallable();
        FutureTask<Integer> futureTask=new FutureTask<>(myCallable);
        Thread thread=new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
    }
    static class MyCallable implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            Random random=new Random();
            int ret=random.nextInt(10);
            return ret;
        }
    }
}

2.使用lambda表达式

public class Method7 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> future=new FutureTask<>(
                () -> {
                    Random random=new Random();
                    return random.nextInt(99);
                }
        );
        Thread thread=new Thread(future);
        thread.start();
        System.out.println(future.get());
    }
}

二、线程中断

2.1通过自定义标记符中断

public class Method1 {
    private static volatile boolean  flag=true;

    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程启动!");
                while (flag){
                }
                System.out.println("线程关闭!");
            }
        });
        thread.start();
        Thread.sleep(100);
        flag=false;
    }
}

但自定义中断标识符的问题在于:线程中断的不够及时。因为线程在执行过程中,无法调用 while(!isInterrupt) 来判断线程是否为终止状态,它只能在下一轮运行时判断是否要终止当前线程,所以它中断线程不够及时,比如以下代码

public class Method1 {
    private static volatile boolean  flag=true;

    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程启动!");
                while (flag){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我偏要捣乱!");
                }
                System.out.println("线程关闭!");
            }
        });
        thread.start();
        Thread.sleep(100);
        flag=false;
    }
}

我们想要的结果是线程开启后直接关闭,但自定义标记符的话必须要执行完while中的代码才能终止线程,导致出现这样的结果
在这里插入图片描述

2.2 通过调用interrupt终止线程

public class Method2 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程启动!");
                while (Thread.currentThread().isInterrupted()){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我偏要捣乱~~~");
                }
                System.out.println("线程关闭!");
            }
        });
        thread.start();
        Thread.sleep(100);
        thread.interrupt();
    }
}

在这里插入图片描述
采用这种方法,就不会出现自定义标记符那种问题,但值得注意的是,在while中,我们还可以这样写while(Thread.interrupted());不一样的是这样调用的是静态方法,再调用之后会清除标记符。
在这里插入图片描述

三、线程等待join

线程等待我们使用的是join方法,某个线程调用这个方法表示下一个线程要等待这个线程执行之后才能执行。
在这里插入图片描述

public class Method {
    public static void main(String[] args) {
        Thread thread1=new Thread(()->{
            System.out.println("thread1开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread1结束执行");
        });
        Thread thread2=new Thread(()->{
            System.out.println("thread2开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread2结束执行");
        });
        thread1.start();
        thread2.start();
    }
}

如果代码正常执行,可能会出现这样的情况:
在这里插入图片描述
但稍微改动。Thread1使用join方法,那么Thread2就会等待Thread1执行结束后执行

public class Method {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1=new Thread(()->{
            System.out.println("thread1开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread1结束执行");
        });
        Thread thread2=new Thread(()->{
            System.out.println("thread2开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread2结束执行");
        });
        thread1.start();
        //改动的代码
        thread1.join();
        thread2.start();
    }
}

结果如下:
在这里插入图片描述

四、线程休眠

4.1使用sleep方法休眠

这种方法直接传递毫秒级别的参数,在我们需要休眠一小时或者一天的时候,需要通过计算的出毫秒数,非常不方便,所以我们可以使用TimeUnit

public class Method1 {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

4.2使用TimeUnit方法休眠

TimeUnit下提供了天、小时等时间单位供我们选择,在进行实际休眠的时候就不用计算,更加便捷

public class Method2 {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

在这里插入图片描述

五、获取线程实例

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(()->{
            System.out.println("线程开启");
        });
        thread.start();
        thread.setName("线程1");
        thread.setPriority(3);
        System.out.println("线程名:"+thread.getName());
        System.out.println("线程id:"+thread.getId());
        System.out.println("线程优先级:"+thread.getPriority());
        Thread.sleep(1000);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

友农

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

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

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

打赏作者

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

抵扣说明:

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

余额充值