多线程的相关知识及代码的实现

1.首先知道实现线程的两种方式,正确来说应该是三种,但第三种不是很常用,我这里就省略不说了!

    实现线程的常用方式就两种 1.继承Thread;2.实现Runnable接口;这两种又有什么区别啊?

    首先你要清楚继承和接口的区别,那么你知道一定的区别啦!但主要的区别就是线程里空间数据的共享问题,只有实现Runnable才能实现数据共享的!肯定还有其他,这里就省     略啦!


2.这里我主要说的是实现Runnable接口的线程实现!这里是我编辑的代码,希望对你学习多线程有帮助!


//测试 运行
public class Test {


public static void main(String[] args) {
//锁定对象同步 
PC pc=new PC();
product p=new product(pc);
custome c=new custome(pc);
Thread a=new Thread(p,"生产者:");
Thread b=new Thread(c,"消费者:");
System.out.println("程序开始运行!\n");
a.start();
b.start();


}

}


//总方法
class PC{
//产品
public static int apple;

//生产者生产方法
public synchronized void add(){

//当生产到一定数额时 停止生产 使其线程处于等待状态
if(apple==20){
try {
System.out.println("生产过度 ,停止生产!");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//当查询到产品到消费到一定额数时 为生产产品添加生产的条件
if(apple<=6){
System.out.println("生产产品中: "+apple);
apple++;
}
//唤醒这个对象等待的线程
this.notify();


}

//消费者消费方法
public synchronized void jian(){

//当消费到一定数额时 停止消费 使其线程处于等待状态
if(apple<=3){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//消费产品
System.out.println("产品消费中: "+apple);
apple--;

}
//唤醒这个对象等待的线程
this.notify();


}





//生产者
class product implements Runnable{
    protected PC pc;
    public product(PC pc){
    this.pc=pc;
    }
@Override
public void run() {
//调用对象的生产方法
while (true) {

pc.add();
try {
Thread.sleep(1000);//睡眠 
} catch (InterruptedException e) {
e.printStackTrace();
}
}



}
}


//消费者
class custome implements Runnable{
    protected PC pc;
    public custome(PC pc){
    this.pc=pc;
    }
@Override
public void run() {
  
while (true) {
//调用对象的消费方法
pc.jian();
try {
Thread.sleep(2000);//睡眠
} catch (InterruptedException e) {

e.printStackTrace();
}
}

}
}

效果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl+C+V程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值