Java基础(31)等待唤醒机制、线程池、定时器

1. 等待唤醒机制

1. 等待唤醒机制的引入在这里插入图片描述

2. 等待唤醒机制

(1)带有线程安全问题、不是等待唤醒机制的代码

public class TestDemo01 {
    public static void main(String[] args) {
        Student student = new Student();
        SetStudentThread th1 = new SetStudentThread(student);
        GetStudentThread th2 = new GetStudentThread(student);

        th1.start();
        th2.start();

        /**运行结果
         *      张三===44    错误
         *      张三===33
         *      李四===44
         *      李四===44
         *      张三===33
         *      张三===44    错误
         *      李四===44
         *      张三===33
         *      李四===44
         *
         *      很明显出现错误 
         */
    }
}

class Student{
    public String name;
    public int age;

    //定义一个标记,用来表示是否有资源
    //false表示没资源,true表示有资源
    public boolean falg = false;
}


//生成者线程:如果有了资源,我要等着,还得通知消费线程去消费。
class SetStudentThread extends Thread{
    private Student student;
    int i = 1;

    public SetStudentThread(Student student) {

        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            if (i % 2 == 0){
                //生产资源
                student.name = "张三";
                student.age = 33;
            }else {
                //生产资源
                student.name = "李四";
                student.age = 44;
            }
            i++;
        }
    }
}


//消费者线程:如果没有资源,就等着,通知生成者去生产资源
class GetStudentThread extends Thread{
    private Student student;

    public GetStudentThread(Student student) {

        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            System.out.println(student.name + "===" + student.age);
        }
    }
}

(2)没有线程安全问题、但不是等待唤醒机制的代码

public class TestDemo01 {
    public static void main(String[] args) {
        Student student = new Student();
        SetStudentThread th1 = new SetStudentThread(student);
        GetStudentThread th2 = new GetStudentThread(student);

        th1.start();
        th2.start();
    }
}

class Student{
    public String name;
    public int age;

    //定义一个标记,用来表示是否有资源
    //false表示没资源,true表示有资源
    public boolean flag = false;
}


//生成者线程:如果有了资源,我要等着,还得通知消费线程去消费。
class SetStudentThread extends Thread{
    private Student student;
    int i = 1;

    public SetStudentThread(Student student) {

        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            synchronized (student){
                if (i % 2 == 0){
                    //生产资源
                    student.name = "张三";
                    student.age = 33;
                }else {
                    //生产资源
                    student.name = "李四";
                    student.age = 44;
                }
            }

            i++;
        }
    }
}


//消费者线程:如果没有资源,就等着,通知生成者去生产资源
class GetStudentThread extends Thread{
    private Student student;

    public GetStudentThread(Student student) {

        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            synchronized (student){
                System.out.println(student.name + "===" + student.age);
            }

        }
    }
}

(3)等待唤醒机制的代码:学生对象为例

void wait()/void wait(long timeout):在其他线程调用此对象的 notify () 方法或 notifyAll () 方法前,导致当前线程等待
void notify():唤醒在此对象监视器上等待的单个线程。
void notifyAll():唤醒在此对象监视器上等待的所有线程。
public class TestDemo01 {
    public static void main(String[] args) {
        Student student = new Student();
        SetStudentThread th1 = new SetStudentThread(student);
        GetStudentThread th2 = new GetStudentThread(student);

        th1.start();
        th2.start();

        /**运行结果
         *      张三===33
         *      李四===44
         *      张三===33
         *      李四===44
         *      张三===33
         *      李四===44
         *      张三===33
         */
    }
}

class Student{
    public String name;
    public int age;

    //定义一个标记,用来表示是否有资源
    //false表示没资源,true表示有资源
    public boolean flag = false;
}


//生成者线程:如果有了资源,我要等着,还得通知消费线程去消费。
class SetStudentThread extends Thread{
    private Student student;
    int i = 1;

    public SetStudentThread(Student student) {

        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            synchronized (student){
                if (student.flag){
                    //有资源,生产者线程就等待
                    try {
                        student.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //没有资源则生产资源
                if (i % 2 == 0){
                    //生产资源
                    student.name = "张三";
                    student.age = 33;
                }else {
                    //生产资源
                    student.name = "李四";
                    student.age = 44;
                }

                //生产完资源后通知消费者线程去消费资源
                //修改标记
                student.flag = true;
                student.notify();   //通知唤醒消费者
            }

            i++;
        }
    }
}


//消费者线程:如果没有资源,就等着,通知生成者去生产资源
class GetStudentThread extends Thread{
    private Student student;

    public GetStudentThread(Student student) {
        this.student = student;
    }

    @Override
    public void run() {
        while (true){
            synchronized (student){
                if (! student.flag){  //false
                    //消费者没有资源,就等着
                    try {
                        student.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //有了资源就消费
                System.out.println(student.name + "===" + student.age);

                //消费后就没有了
                //通知生产者去生产
                student.flag = false;
                student.notify();
            }

        }
    }
}

(4)等待唤醒机制的代码:吃包子为例

public class DemoEatBaozi {
    public static void main(String[] args) {
        BaoZi bz = new BaoZi();
        new BaoZiPu(bz).start();
        new ChiHuo(bz).start();
    }
}

class BaoZi{
    String pi;
    String xian;
    //设置包子的状态,true:有包子 false:没包子
    boolean flag = false;   //默认没包子
}

class BaoZiPu extends Thread{
    //1.定义一个包子变量
    private BaoZi bz;

    public BaoZiPu(BaoZi bz) {
        this.bz = bz;
    }

    //生产包子
    @Override
    public void run() {
        int count = 0;

        while (true){
            synchronized (bz){
                if (bz.flag == true){   //有包子则等待
                    try {
                        bz.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //被唤醒之后执行,生产包子
                if (count % 2 == 0){
                    //生产薄皮三鲜馅包子
                    bz.pi = "薄皮";
                    bz.xian = "三鲜";
                }else {
                    //生产冰皮牛肉大葱馅
                    bz.pi = "冰皮";
                    bz.xian = "牛肉大葱";
                }

                count++;

                System.out.println("包子铺正在生产" + bz.pi + bz.xian + "的包子");
                //生产包子需要3秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //改状态
                bz.flag = true;
                //唤醒等待的吃货线程
                bz.notify();
                System.out.println("已经生产了好了" + bz.pi + bz.xian + "的包子,可以开始吃了");
            }
        }
    }
}


class ChiHuo extends Thread{
    private BaoZi bz;

    public ChiHuo(BaoZi bz) {
        this.bz = bz;
    }

    @Override
    public void run() {
        while (true){
            synchronized (bz){
                if (bz.flag == false){  //没包子,等待
                    try {
                        bz.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //被唤醒之后
                System.out.println("吃货正在吃" + bz.pi + bz.xian + "的包子");

                //吃完后修改状态
                bz.flag = false;

                //唤醒包子铺线程
                bz.notify();
                System.out.println("吃货已经吃完了包子,包子铺已经开始生产包子了");
                System.out.println("--------------------------------");
            }
        }
    }
}

3. 线程的状态
在这里插入图片描述

4. 匿名内部类来开启线程

public class TestDemo02 {
    public static void main(String[] args) {
        Thread th1 = new Thread() {
            @Override
            public void run() {
                System.out.println("匿名内部类创建的线程--111");
            }
        };
        th1.start();

        System.out.println("-------------------------");

        new Thread(){
            @Override
            public void run() {
                System.out.println("匿名内部类创建的线程--222");
            }
        }.start();

        System.out.println("-------------------------");

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名内部类创建的线程--333");
            }
        }).start();
    }
}

2. 线程池

1. 线程池的概述:
(1)线程池:容器,存有一定数量线程对象的容器,线程池可以复用管理线程对象
(2)使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池
(3)线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用
(4)从JDK5开始,Java内置支持线程池

2. 线程池的使用:
(1)生产线程池

JDK1.5新增了一个Executors工厂类来产生线程池,有如下几个方法
	public static ExecutorService newCachedThreadPool():根据任务的数量来创建线程对应的线程个数	
	public static ExecutorService newFixedThreadPool(int nThreads):固定初始化几个线程
	public static ExecutorService newSingleThreadExecutor():初始化一个线程的线程池

(2)使用方法

	Future<?> submit(Runnable task):添加线程
	<T> Future<T> submit(Callable<T> task):添加线程
	void shutdown():关闭线程池

(3)代码示例

public class TestDemo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //public static ExecutorService newCachedThreadPool():根据任务的数量来创建线程对应的线程个数
        ExecutorService es1 = Executors.newCachedThreadPool();
        es1.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行了这个任务");
            }
        });   //pool-1-thread-1执行了这个任务

        Future<Integer> future = es1.submit(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                System.out.println("call方法执行了");
                return 200;
            }
        });    //call方法执行了

        Integer i = future.get();
        System.out.println(i);   //200


        System.out.println("===================================================");

        ExecutorService es2 = Executors.newFixedThreadPool(2);
        es2.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "哈哈哈");
            }
        });    //pool-2-thread-1哈哈哈

        es2.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "呵呵呵");
            }
        });   //pool-2-thread-2呵呵呵


        System.out.println("===================================================");

        //public static ExecutorService newSingleThreadExecutor():初始化一个线程的线程池
        ExecutorService es3 = Executors.newSingleThreadExecutor();
        es3.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "德玛西亚!");
            }
        });    //pool-3-thread-1德玛西亚!

        es3.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "诺克萨斯!");
            }
        });    //pool-3-thread-1诺克萨斯!

    }
}

3. Timer定时器

1. Timer定时器的概述:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。可以通过Timer和TimerTask类来实现定义调度的功能

2. Timer和TimerTask

Timer:
		public Timer()
		public void schedule(TimerTask task, long delay):	
		public void schedule(TimerTask task,long delay,long period);
		public void schedule(TimerTask task,  Date time):
		public void schedule(TimerTask task,  Date firstTime, long period)
TimerTask:定时任务
		public abstract void run()
		public boolean cancel()

3. 代码示例

public class TestDemo01 {
    public static void main(String[] args) {
        Timer timer = new Timer();

        MyTimeTask mtt = new MyTimeTask(timer);

//        //3s后执行任务
//        timer.schedule(mtt,3000);

        //3秒后执行任务,且每隔1秒执行一次
        timer.schedule(mtt,3000,1000);
    }
}

class MyTimeTask extends TimerTask{

    private Timer timer;

    public MyTimeTask(Timer timer) {

        this.timer = timer;
    }

    @Override
    public void run() {
        System.out.println("定时器执行了!");
    }
}

===============================================================================================

public class TestDemo02 {
    public static void main(String[] args) throws ParseException {
        Timer timer = new Timer();

        MyTask mt = new MyTask();

        String dateStr = "2020-6-10 10:22:00";
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);


        //在2020-6-10 10:22:00执行定时器任务
        timer.schedule(mt,date);
        
    }
}

class MyTask extends TimerTask{


    @Override
    public void run() {
        System.out.println("定时器任务执行了!");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值