(个人笔记)Thread

本文探讨了如何在Java中通过继承Thread类实现多线程,并通过Box类的生产者消费者模式展示了线程间的同步与协作。Box类中的put和get方法使用synchronized关键字实现了互斥,确保了资源安全。Consumer和Producer类作为线程实例,演示了并发场景的实际操作。
摘要由CSDN通过智能技术生成

继承实现多线程

public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();

        mt1.start();
        mt2.start();
    }
}
public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i=0; i<100; i++)
        {
            System.out.print(i+" ");
        }
    }
}

消费者案例

Box类

public class Box {
    private  int milk;
//    定义一个成员变量,表示奶箱的状态
    private boolean state = false;

    public synchronized void put(int milk){
//        如果有牛奶 ,等待消费
        if (state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//      如果没有牛奶,就放入牛奶
        this.milk = milk;
        System.out.println("送奶工将第"+this.milk+"瓶奶放入奶箱");
//        放入完毕,修改奶箱的状态
        state = true;
//        唤醒其他等待的线程
        notifyAll();
    }
    public synchronized void get(){
//        如果没有牛奶,等待放入牛奶
        if (!state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//        如果有牛奶就取出牛奶
        System.out.println("用户拿到第"+this.milk+"瓶奶");
//        取出牛奶,修改奶箱状态
        state = false;
//        唤醒其他等待的线程
        notifyAll();
    }

}

Customer类

public class Customer implements Runnable {
    private Box b;

    public Customer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        while (true) {
            b.get();
        }
    }
}
Producer类
public class Producer implements Runnable {
    private Box b;

    public Producer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            b.put(i);
        }
    }
}

测试类

public class BoxDemo {
    public static void main(String[] args) {
//        创建奶箱对象————共享数据区域
        Box b = new Box();
//        创建生产者对象
        Producer p = new Producer(b);
//        创建消费者对象
        Customer c = new Customer(b);
//        创建两个线程对象
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);

//        启动线程
        t1.start();
        t2.start();


    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值