Java-线程

1.java线程的实现常用的两种方式:

  • 继承Thread类,重写run方法。
  • 实现Runable接口,实现run方法。然后通过Thread创建线程对象,并将实现Runable接口的子类作为实际参数传给Thread的构造函数。

2.多线程使用(生产者和消费者)

public class ProduceOneCusumer {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        Resource r = new Resource();
        Producer pro = new Producer(r);
        Consumer con = new Consumer(r);
        Thread t1 = new Thread(pro);//生产者线程
        Thread t2 = new Thread(pro);
        Thread t3 = new Thread(con);//消费者线程
        Thread t4 = new Thread(con);
        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }

}
/**
 * 仓储类,仓储原料
 * @author Administrator
 *
 */
class Resource{
    private String name;//原料名称
    private int count = 1;//生产数量
    private boolean flag = false;
    
    public synchronized void set(String name){//t1
        while(flag){
            try {
                this.wait();//仓库满了,生产者等待,等待消费者消费
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name+"------"+count++;
        System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
        this.flag = true;
        // this.notify();//唤醒消费者线程进行消费
        this.notifyAll();
        
    }
    public synchronized void out(){//t2,t3
        while(!flag){//false
            try {
                this.wait();//仓库为空不能消费,消费者线程等待,等待生产者生产
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"......消费者......."+this.name);
        this.flag = false;
        // this.notify();//唤醒生产者
        this.notifyAll();
    }
}

/**
 * 生产者类
 * @author Administrator
 *
 */
class Producer implements Runnable{
    private Resource r;
    public Producer(Resource r){//把原料放到生产者里面生产,当生产者一创建生产对象,就初始化原料
        this.r = r;
    }
    @Override
    public void run() {
        while(true){//不断的生产
            r.set("烤鸭");//生产烤鸭
        }
    }
}

class Consumer implements Runnable{
    private Resource r;
    public Consumer(Resource r){
        this.r = r;
    }

    @Override
    public void run() {
        while(true){
            r.out();//消费者消费
        }
    }
    
}
原文地址:https://www.cnblogs.com/king-peng/p/10048367.html