集合作为被多线程访问的数据集合,提供对外的方法供不同的线程的调用,
关键不是集合的同步的问题,主要还是多线程的同步问题。
以经典的生产者消费者这个为样板理解:
- public class WaitNotifyDemo {
- public static void main(String[] args) {
- Resource res = new Resource("商品");
- Producer pro = new Producer(res);
- Customer cus = new Customer(res);
- new Thread(pro).start();
- new Thread(cus).start();
- new Thread(pro).start();
- new Thread(cus).start();
- }
- }
- class Producer implements Runnable {
- private Resource res;
- Producer(Resource res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (true) {
- res.setRes();
- }
- }
- }
- class Customer implements Runnable {
- private Resource res;
- Customer(Resource res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (true) {
- res.getRes();
- }
- }
- }
- class Resource {
- private String name;
- private int count;
- private boolean flag; // flag表示是否存在资源
- Resource(String name) {
- this.name = name;
- count = 0;
- flag = false;
- }
- public void setFlag(boolean flag) {
- this.flag = flag;
- }
- public synchronized void setRes() {
- while(this.flag) { //注意要使用while而不是使用if来控制判断,当线程从wait状态醒来需要重新判断flag
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println("生产者---------" + Thread.currentThread().getName()
- + this.name + " " + (++count));
- setFlag(true);
- notifyAll();
- }
- public synchronized void getRes() {
- while (!this.flag) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println("消费者" + Thread.currentThread().getName()
- + this.name + " " + count);
- setFlag(false);
- notifyAll();
- }
- }
复制代码
那么集合可以看作是这里面的Resource 类了 ,
不知道我的看法是不是正确,一起学习 |