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

来源:互联网 发布:彩虹控制软件 编辑:程序博客网 时间:2024/06/09 17:12

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();
}
}

}
}

效果图:



0 0