线程并发 经典例子 生产者与消费者
回顾了一下---- 很久以前的只是
常用的:
1、synchronized 修饰方法 ,
2、synchronized 代码块 ---------- 属于对象 1,2 功能一样 只不过 代码块修饰的 比较方便
2、static synchronized 修饰方法 --------属于类
结论:A: synchronized static是某个类的范围,synchronized static cSync{}防止多个线程同时访问这个 类中的synchronized static 方法。它可以对类的所有对象实例起作用。 B: synchronized 是某实例的范围,synchronized isSync(){}防止多个线程同时访问这个实例中的synchronized 方法。
所以 同一对象 两个线程访问 a方法 synchronized 修饰 ; b方法 static synchronized 修饰 不存在同步的
-----------------------------讲主题吧 生产者 消费者
/** * 工厂队列 * @author Crayon * Created by 2018-12-20 */ public class Queue { private int n; private boolean flag = false; // 控制值 默认为 生产模式 /** * 消费 * @return */ public synchronized int getN() { if(!flag) { try { wait(); // 线程等待 只有为true 才消费 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("消费:"+n); flag = false; notifyAll(); return n; } /** * 生产 * @return */ public synchronized void setN(int n) { if(flag) { try { wait(); // 线程等待 只有为false 才干活 生产 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("生产:"+n); this.n = n; flag = true; notifyAll(); //释放 wait() } }
public class Product implements Runnable { private Queue queue; public Product(Queue queue) { this.queue = queue; } @Override public void run() { int i=0; while(true) { queue.setN(++i); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class Consumer implements Runnable { private Queue queue; public Consumer(Queue queue) { this.queue = queue; } @Override public void run() { while(true) { queue.getN(); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
public class Test { public static void main(String[] args) { Queue queue = new Queue(); //开始线程测试 new Thread(new Consumer(queue)).start(); new Thread(new Product(queue)).start(); } }
效果如下:
实现 同步。。。
上一篇:
IDEA上Java项目控制台中文乱码