【java多线程】Thread的基本用法


一、线程的创建

线程的创建有4种方法

1.通过继承Thread类

class MyThread extends Thread{
	//这个方法就是线程的入口方法
    @Override
    public void run() {
    }
}

2.通过实现Runnable接口

class MyRunnable implements Runnable{
    @Override
    public void run() {

    }
}

3. 通过匿名内部类继承Thread类

Thread thread = new Thread() {
    @Override
    public void run() {
        
    }
};

4. 通过匿名内部类实现Runnable接口(此处使用lambda表达式)

Thread thread = new Thread(() -> {
        
    }
);

二、线程的中断

让线程中断的方法是唯一的, 那就是让线程run方法结束
而影响run方法执行时间的首要因素之一就是其中的循环体代码
所以我们需要设法让循环体结束

方法一

public class Demo8 {
    private static boolean isQuit = false;
    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(() -> {
           while (!isQuit){
               System.out.println("线程工作中");
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
            System.out.println("线程工作完毕");
        });
        thread.start();
        Thread.sleep(5000);
        System.out.println("设置isQuit为ture");
        isQuit = true;
    }
}

如上述代码, 我们维护一个isQui变量, 让其成为测试线程循环体的条件
这样我们就可以控制循环体结束了

但这样写的代码并不优雅,而且当循环体中有休眠时,就算修改了isQiut循环体也不能马上结束

方法二

另一种方法是我们可以调用Thread对象的interrupt()方法来让线程中断
(Thread.currentThread()方法获取的是当前的线程对象, isInterrupted()方法返回为该线程是否被中断)

public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("thread is working");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    //1.假装没听见,循环继续进行
                    e.printStackTrace();
                    //2. 加上一个break
                    //break;
                    //3. 做一些其他工作完成后再结束
                }
            }
        });
        thread.start();
        Thread.sleep(5000);
        System.out.println("let thread be interrupted");
        thread.interrupt();

    }
}

这样写不仅让代码更加优雅了, 而且还可以让休眠提前停止, 那是怎么让休眠提前停止的呢, 且听我娓娓道来
当我们手动调用线程对象的interrupt()方法后, 会触发sleep方法的内部异常, 让休眠停止,
不过让休眠停止的同时, 还顺手将刚才手动设置的标志位给还原了, 于是循环体又可以继续运行了

在这里插入图片描述
看程序运行结果
触发异常后循环体又继续了
必须在捕获异常后catch代码块内加上break;才能真正退出循环

三、线程等待

其实就是线程对象的 join() 方法
这个方法的使用很简单 哪个线程调用这个方法 哪个线程 就等待 该线程对象的线程执行结束才能执行自己的代码(ps:可以在()内放参数设置超时时间)
举个栗子:

public class Demo10 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("thread is working");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        System.out.println("start waiting");
        thread.join();
        System.out.println("end waiting");
    }
}

因为在主线程中调用了thread.join();所以主线程必须等待thread线程执行完毕了才能执行自己的代码
程序运行结果:

start waiting
thread is working
thread is working
thread is working
thread is working
thread is working
end waiting

四、程序休眠

就是Thread.sleep()方法啦
这个方法是以毫秒为单位让线程进行休眠

五、获取线程实例

在之前我们获取当前线程的标志位时用到了Thread.currentThread()方法
这个方法可以返回当前代码是在哪个线程上跑

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值