线程的应用

线程的应用

java中,我们应该如何使用多线程。

  • 继承Thread,通过start方法启动一个线程
  • 实现Runnable接口,将实现类塞进Thread构造方法中,通过start方法启动。
  • 使用ExecutorServiceCallableFuture来实现带有返回结果的线程。

继承Thread类创建线程

public class ThreadDemo extends Thread{
    @Override
    public void run() {
        System.out.println("通过继承 Thread 创建的线程");
    }

    public static void main(String[] args) {
        new ThreadDemo().start();//启动一个线程
    }
}

run方法体中需要实现你希望这个线程驱动的任务,在以上例子中,我们只需要这个ThreadDemo打印一句话即可。

实现Runnable接口创建线程

public class RunnableDemo implements Runnable{

    public void run() {
        System.out.println("实现Runnable 接口所创建");
    }

    public static void main(String[] args) {
        new Thread(new RunnableDemo()).start();
    }
}

相比继承,实现接口的方式更具有灵活性,实现Runnable方法中run完成接口的实现,接着塞进Thread的构造器中。

实现Callable接口

有时候,我需要线程执行完后,给我一个反馈,那么带有返回值的线程是个好选择。我们可以根据返回值来做一些后续逻辑处理。

public class CallableDemo implements Callable<String> {

    public String call() throws Exception {
        return String.valueOf(1+1);//简单计算一下1+1
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建核心线程数与最大线程数为1个的线程池
        ExecutorService executorService= Executors.newFixedThreadPool(1);
        CallableDemo callableDemo = new CallableDemo();
        //活动返回任务
        Future<String> future = executorService.submit(callableDemo);
        //打印出结果
        System.out.println(future.get());//在未得到数据之前阻塞
        executorService.shutdown();//销毁线程池中的线程

    }
}

说了那么多,我们在日常生活中很少用到多线程,不过这并不能阻止我们去了解更多

他的原理,下面是一个简单例子,我们使用阻塞队列来完成一个责任链模式。

public class Request {//模拟一个请求。
    private String name;

    @Override
    public String toString() {
        return "Request{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

然后,我们定义两个用于处理请求的线程,首先按照规范,我们来定义一个接口

public interface RequestProcessor {
    void processRequest(Request request);
}

一个实现用于打印这个请求的类和存储这个请求的类,用来模拟某个网络请求过来,我们会他进行日志的分析和入库。

public class PrintProcessor extends Thread implements  RequestProcessor{

    //定义一个阻塞队列
    LinkedBlockingQueue<Request> requests =
            new LinkedBlockingQueue<Request>();

    //我们将定义下一个请求,构成责任链
    private final RequestProcessor next;

    public PrintProcessor(RequestProcessor next) {
        this.next = next;
    }

    @Override
    public void run() {
        while(true){

            try {
                //如果阻塞队列没有可取出的request,将会被阻塞
                Request request = requests.take();
                System.out.println("print Data:"+request.getName());
                //调用下一条请求
                next.processRequest(request);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public void processRequest(Request request) {
            requests.add(request);//将请求添加到阻塞队列
    }
}

public class SaveProcesspr extends Thread implements RequestProcessor{

    LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<Request>();

    @Override
    public void run() {
        while(true){

            try {
                //如果阻塞队列没有可取出的request,将会被阻塞
                Request request = requests.take();
                System.out.println("save Data:"+request.getName());
                //调用下一条请求
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public void processRequest(Request request) {
            requests.add(request);
    }
}

启动

public class Boostrap {

    PrintProcessor printProcessor;

    protected Boostrap(){
        SaveProcesspr saveProcesspr = new SaveProcesspr();
        saveProcesspr.start();//启动的时候,由于阻塞队列没有request请求,该线程将会被阻塞
        printProcessor = new PrintProcessor(saveProcesspr);
        printProcessor.start();
        //printProcessor将saveProcessper作为下一个节点
        //也同样,当前阻塞队列中没有数据,将会被阻塞
    }

    private  void addRequest(Request request){
        printProcessor.processRequest(request);
    };

    public static void main(String[] args) {
        Request request = new Request();
        request.setName("Pop");
        new Boostrap().addRequest(request);
        //随着请求的加入,进入printProcessor的阻塞队列,run方法将重新执行
        //并且通过saveProcessor的processRequest的方法再次入队列,接着进行
        //存储操作
        //当消费完后,两个线程会再次因为requet被消费完而进行阻塞,直到下一个请求
        //入队列
    }

}

以上,我们通过阻塞队列和责任链完成了一个简单的请求分析和入库的简单操作。但我们仍需了解里面的具体机制。

JAVA中的并发基础

我们在上面的例子中,创建了线程,并且使他们为我们驱动了一些简单的任务,如果渴望更加深入了解这门技术,最好的入口应该就是生命周期。

对于Java的线程生命周期,他从创建到销毁有6种状态:NEWRUNNABLEBLOCKED

WAITINGTIME_WAITINGTERMINATED。

我画了一个图帮助理解。

在这里插入图片描述

在上面的图上,我还标注了哪些方法可以使得线程分别进入什么状态,可以说api提供了很多方式帮助我们可以自由的操控线程的状态。

我们可以通过继承Thread来使得某一个类具备启动线程的能力,当我们new Thread()的时候,这个线程已经准备就绪(ready),但是这个时候线程并没有启动,只不过是处于可以运行(Runnable)的状态,当你使用.start()方法的时候,这个线程就处于运行状态(Runnable)。

当然,线程生命周期一定没有那么简单,他的一生也可以是坎坷的一生。

BLOCKED:阻塞状态,表示当前线程因为某些因素放弃了CPU的使用权

  • 等待阻塞:运行的线程调用了wait方法
  • 同步阻塞:运行的线程在获取对象的同步锁时,因为锁已经被其他线程抢占,导致竞争失败,而被阻塞。
  • 其他阻塞:运行的线程执行Thread.sleep,或者其他线程的join方法,或者发出了IO请求,当Sleep结束,join结束,或者IO处理完毕后线程恢复
  • TIME_WAITING:超时等待状态,超时以后自动返回
  • TERMINATED:终止状态,表示当前线程执行完毕。
线程的终止

其实上面的五种状态并没有包括TEMMINATE的状态,让线程终止有一些api可以完成,例如stopsuspendresume,可是jdk却不建议这样结束线程。

例如stop方法会比较暴力地关闭线程,如果你的线程这时候存在一些资源还未正常释放,或者其他什么问题,会导致程序可能会出现一些不确定的状态。

那么如何优雅的终止掉一个线程呢?

interrupt

当某个Thread调用,interrupt方法的时,并不会直接中断线程,而是等待他的任务完成后再去中断。

使用interrupt方法,一般要配合isInterrupted进行使用,因为interrupt只是对线程的一种建议,如果该线程处于无法被中断的状态,就会抛出异常InterruptedException,例如该线程处于阻塞,或者等待状态。

如果你期待你的interrupt有可见的作用,务必配合Thread.currentThread.isInterrupted()来使用。

public class InterruptedDemo extends Thread{

    public static void main(String[] args) throws InterruptedException {
        InterruptedDemo thread = new InterruptedDemo();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println("没有标志");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

在这里插入图片描述
有标志的情况

public class InterruptedDemo1 extends Thread{

    public static void main(String[] args) throws InterruptedException {
        InterruptedDemo1 thread = new InterruptedDemo1();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            try {
                Thread.sleep(1000);
                System.out.println("有标志");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

在这里插入图片描述

第一个例子,我们并没有加上,Thread.currentThread().isInterrupted(),即便我们调用了interrupt也没有任何反应,因为他抛出了异常,表示我的任务没有结束,你不能终止我。

但是第二个例子,却能够正常结束,原因是interrupt所发出的建议,被

Thread.currentThread().isInterrupted()观察到了,所以才能跳出循环,完成任务后退出。

所以,我们可以认为,线程中存在某一个interrupted标识,能够将改变这个线程可被中断的描述,初始值应该为false,因为一开始线程运行并不是中断状态,当调用

interrupt方法的时候,标识改变,通过Thread.currentThread().isInterrupted()获得标识现在的结果。

interrupted

既然有中断的建议,那可以不可以有反悔的建议呢。

例如对某个线程说了你可以自行了断了,然后中断标识符设置成了true,表示这个线程可以中断了,但是我中途改变了主意,对不起,刚刚的建议请你没听见,我现在将你的中断表示符改回去,你可以不用中断了

我们把这种操作叫做复位

复位后的线程和当初没什么两样,因为他们就好像没听到过中断建议一样。

public class InterruptedDemo2 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread  = new Thread(()->{
            while(true){

                if(Thread.currentThread().isInterrupted()){//如果标识已经改变成了中断

                    System.out.println("before "+Thread.currentThread().isInterrupted());

                    boolean interrupted=Thread.interrupted();//复位,将标识改成false
                    System.out.println("返回的标志: "+interrupted);

                    System.out.println("after "+Thread.currentThread().isInterrupted());
                }

            }
        });
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

在这里插入图片描述

我们可以看到,我们的interrupt建议同样没有任何作用,因为通过Thread.interrupted复位了,并且这个方法是有返回值的,调用的时候,他将返回当前的中断状态,并且复位。

其它的复位方式

public class InterruptedDemo3 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread  = new Thread(()->{
            for(;;){
                if(!Thread.currentThread().isInterrupted()){
                    try {
                        TimeUnit.SECONDS.sleep(2);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("异常抛出后"+Thread.currentThread().isInterrupted());
                    }
                }
            }

        });
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

在这里插入图片描述
我们抛出异常的时候,同样也会将中断标识复位。

总结
  • 线程的创建
    • 继承Thread
    • 实现Runnable
    • 实现Callable,与Future,完成带有返回值的线程
  • 线程的生命周期
    • new
    • running
    • block
    • waiting
    • time_waiting
    • terminate
  • 操控线程的方式
    • start 启动一个线程
    • interrupt 尝试中断一个线程
    • interrupted 复位一个线程

源码链接

每天积累一点点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值