Java学习笔记——Java语言基础(二十三)(线程间的通信、线程池、Timer类)

一、线程间的通信

当多个线程处理用一个资源时,每个线程的任务却不相同,这时就是线程间的通信问题。
为什么要处理线程间通信?
多个线程并发执行时, 在默认情况下CPU是随机切换线程的,当我们需要多个线程来共同完成一件任务,并且我们希望他们有规律的执行, 那么多线程之间需要一些协调通信,以此来帮我们达到多线程共同操作一份数据。
保证线程间通信有效利用资源——等待唤醒机制
多个线程在处理同一个资源,并且任务不同时,需要线程通信来帮助解决线程之间对同一个变量的使用或操作。 就是多个线程在操作同一份数据时, 避免对同一共享变量的争夺
在一个线程进行了规定操作后,就进入等待状态(wait()), 等待其他线程执行完他们的指定代码过后 再将其唤醒(notify());在有多个线程进行等待时, 如果需要,可以使用 notifyAll()来唤醒所有的等待线程。
等待唤醒机制就是用于解决线程间通信的问题的,使用到的3个方法:

1. wait:线程不再活动,不再参与调度,进入 wait set 中,因此不会浪费 CPU 资源,也不会去竞争锁了,这时的线程状态即是 WAITING。它还要等着别的线程执行一个特别的动作,也即是“通知(notify)”在这个对象上等待的线程从wait set 中释放出来,重新进入到调度队列(ready queue)中
2. notify:则选取所通知对象的 wait set 中的一个线程释放;
3. notifyAll:则释放所通知对象的 wait set 上的全部线程。

调用wait和notify方法需要注意的细节

1. wait方法与notify方法必须要由同一个锁对象调用。因为:对应的锁对象可以通过notify唤醒使用同一个锁对象调用的wait方法后的线程。
2. wait方法与notify方法是属于Object类的方法的。因为:锁对象可以是任意对象,而任意对象的所属类都是继承了Object类的。
3. wait方法与notify方法必须要在同步代码块或者是同步函数中使用。因为:必须要通过锁对象调用这2个方法。

代码实现:
定义一个包子类:设置包子的属性

public class Baozi {
    String pi;
    String xian;
    //设置初始值状态
    boolean flag=false;
}

定义一个吃包子类:

public class ChiHuo extends Thread{
    private Baozi baozi;
    // 2.使用构造方法,对于包子变量赋值
    public ChiHuo(Baozi baozi) {
        this.baozi = baozi;
    }

    @Override
    public void run() {
        while (true){
            synchronized (baozi){
                if (baozi.flag==false){
                    try {
                        baozi.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //线程被唤醒之后
                System.out.println("正在吃包子"+baozi.pi+baozi.xian);

               baozi.flag=false;
               //唤醒包子铺线程
               baozi.notify();
                System.out.println("已经把"+baozi.pi+baozi.xian+"吃完了,包子铺继续生产包子");
                System.out.println("=============");
            }
        }
    }
}

定义包子铺的类:

public class BaoZiPu extends Thread{
    //1.创建包子变量
    private Baozi baozi;
    // 2.使用构造方法,对于包子变量赋值
    public BaoZiPu(Baozi baozi) {
        this.baozi = baozi;
    }

    @Override
    public void run() {
        //定义一个变量
        int conut=0;
        while (true){
            synchronized (baozi){
                if (baozi.flag==true){
                    try {
                        baozi.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //被唤醒之后进行,包子铺生产包子
                if (conut%2==0){
                    //生产一种包子
                    baozi.pi="薄皮";
                    baozi.xian="三鲜";
                }else {
                    baozi.pi="冰皮";
                    baozi.xian="牛肉";
                }
                conut++;
                System.out.println("包子铺正在生产"+baozi.pi+baozi.xian);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                baozi.flag=true;
                //唤醒吃包子的线程
                baozi.notify();
                System.out.println("已经生产完毕"+baozi.pi+baozi.xian);
            }
        }

    }
}

测试类:

public class Test {
    public static void main(String[] args) {
        Baozi baozi = new Baozi();
        new BaoZiPu(baozi).start();
        new ChiHuo(baozi).start();
    }
}

二、线程池

我们使用线程的时候就去创建一个线程,这样实现起来非常简便,如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。
这是我们可以使用线程池来达到我们的需求

2.1 线程池的概念

线程池:其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。
使用线程池的好处:

1. 降低资源消耗。减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
2. 提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。
3. 提高线程的可管理性。可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。

线程池的创建:

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) 
          用给定的初始参数和默认的线程工厂及被拒绝的执行处理程序创建新的 ThreadPoolExecutor。

参数介绍:

corePoolSize:线程池核心线程数量
maximumPoolSize:线程池最大线程数量
keepAliverTime:当活跃线程数大于核心线程数时,空闲的多余线程最大存活时间
unit:存活时间的单位
workQueue:存放任务的队列
handler:超出线程范围和队列容量的任务的处理程序

线程池的实现原理:

1、判断线程池里的核心线程是否都在执行任务,如果不是(核心线程空闲或者还有核心线程没有被创建)则创建一个新的工作线程来执行任务。如果核心线程都在执行任务,则进入下个流程。
2、线程池判断工作队列是否已满,如果工作队列没有满,则将新提交的任务存储在这个工作队列里。如果工作队列满了,则进入下个流程。
3、判断线程池里的线程是否都处于工作状态,如果没有,则创建一个新的工作线程来执行任务。如果已经满了,则交给饱和策略来处理这个任务。

JDK5新增了一个Executors工厂类来产生线程池,ExecutorService 线程池
构造方法:

public static ExecutorService newCachedThreadPool():			根据任务的数量来创建线程对应的线程个数	
public static ExecutorService newFixedThreadPool(int nThreads):	固定初始化几个线程
public static ExecutorService newSingleThreadExecutor():			初始化一个线程的线程池

这些方法的返回值是ExecutorService对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程。

public class MyTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建一个线程池 根据任务的数量来创建线程对应的线程个数
        ExecutorService executorService = Executors.newCachedThreadPool();
        //给线程池提交Runnable任务 提交3个任务 会创建3个线程
        MyRunnable myRunnable = new MyRunnable();
        executorService.submit(myRunnable);
        executorService.submit(new MyRunnable());
        executorService.submit(new MyRunnable());
        //
        Future<?> future = executorService.submit(new MyCallable(100));
        //可以获取返回值
        Integer o = (Integer) future.get();
        //输出1-100相加的和
        System.out.println(o);//5050

        Future<Integer> submit = executorService.submit(new MyCallable(10));
        Integer integer = submit.get();
        System.out.println(integer);
        //关闭线程池
        executorService.shutdown();
    }
}

class MyCallable implements Callable<Integer> {
    int num;
    public MyCallable(int num) {
        this.num=num;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "Callable任务执行了");
        int sum=0;
        for (int i = 0; i <= num; i++) {
            sum+=i;
        }
        return sum;
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Runnable任务执行了");
    }
}

执行结果:
在这里插入图片描述
有结果可以看出,线程池创建了3个线程,当一个线程执行完一个Runnable任务,这个线程可以执行其他的任务。
使用newFixedThreadPool ( int nThreads):固定线程池的线程个数。

public class MyTest2 {
    public static void main(String[] args) {
       // public static ExecutorService newFixedThreadPool ( int nThreads):固定初始化几个线程
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //往线程池提交任务
        executorService.submit(new IRunnable());
        executorService.submit(new IRunnable());
        executorService.submit(new IRunnable());
        executorService.submit(new IRunnable());
        executorService.submit(new IRunnable());
        executorService.submit(new IRunnable());
        //关闭线程池
        executorService.shutdown();
    }
}

class IRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"执行任务");
    }
}

在这里插入图片描述
固定线程的个数为2,当有任务需要执行时,就会提供线程执行该任务,其他任务处于等待状态,等到任务执行结束,该线程执行下一个任务。

三、Timer类

一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

定时器是一个应用十分广泛的线程工具,可用于调度多个定时任务以后台线程的方式执行。在Java中,可以通过Timer和TimerTask类来实现定义调度的功能。
构造方法:

Timer()  	创建一个新计时器。
Timer(String name)  	创建一个新计时器,其相关的线程具有指定的名称。

Timer的方法:

schedule(TimerTask task, Date time)  安排在指定的时间执行指定的任务。
schedule(TimerTask task, Date firstTime, long period)  安排指定的任务在指定的时间开始进行重复的固定延迟执行。
schedule(TimerTask task, long delay)  安排在指定延迟后执行指定的任务。

TimerTask:由 Timer 安排为一次执行或重复执行的任务。
其中的方法

cancel()  取消此计时器任务。
 run()  此计时器任务要执行的操作。

使用1:使用构造方法 schedule(TimerTask task, long delay) 安排在指定延迟后执行指定的任务。

public class MyTimerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入爆炸的时间");
        int i = sc.nextInt();
        int time=i*1000;
        //构造一个计时器
        Timer timer = new Timer();
        System.out.println("提示"+i+"秒后会爆炸");
        //参数1:任务 参数2:等待时间
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("砰~爆炸");
            }
        },time);
        timer.cancel();
    }
}

使用2:将计时器执行完毕之后,取消计时器任务
需要在TimerTask的run方法执行完毕关闭任务

public class MyTimerDemo2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入爆炸的时间");
        int i = sc.nextInt();
        int time=i*1000;
        System.out.println("提示"+i+"秒后会爆炸");
        Timer timer = new Timer();
        timer.schedule(new MyTimerTask(timer),time);
    }
}
class MyTimerTask extends TimerTask{
    Timer timer;
    //参数传递timer可以 取消定时器
    public MyTimerTask(Timer timer) {
        this.timer=timer;
    }
    @Override
    public void run() {
        System.out.println("砰~爆炸");
        timer.cancel();
    }
}

使用3:使用构造方法schedule(TimerTask task, Date time) 安排在指定的时间执行指定的任务。
定时删除文件夹

public class MyTimerDemo3 {
    public static void main(String[] args) throws ParseException {
        Timer timer = new Timer();
        String str = "2020-02-19 15:23:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(str);
        timer.schedule(new MyTimerTask2(timer), date);

    }
}

class MyTimerTask2 extends TimerTask {
    Timer timer;

    //参数传递timer可以 取消定时器
    public MyTimerTask2(Timer timer) {
        this.timer = timer;
    }

    @Override
    public void run() {
        File file = new File("C:\\Users\\asus\\Desktop\\24.【Stream流、方法引用");
        deleteFloder(file);
        timer.cancel();
    }

    private void deleteFloder(File fileFloder) {
        File[] files = fileFloder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            }else {
                deleteFloder(file);
            }
        }
        fileFloder.delete();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值