关于java多线程

多线程

  • 1、当程序单个线程无法解决时,或者效率,或者其他原因时,需要使用多线程。
  • 2、多线程的一些使用方法
    • wait() 方法一般与while,synchronized连用。当程序满足一定条件时,就会进入等待队列,等待的过程释放锁,而后再去竞争。
    • 使用到wait()方法后一般会使用notify进行唤醒。
  • 代码展示:
    • 1、建立线程池
public class ThreadPool {
  private LinkedList<Integer> pool = new LinkedList<>();
  private int MAX = 1;

  public synchronized int add(Integer i) {

      while (pool.size() >= MAX) {
          try {
              wait(1000);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }

      }
      pool.add(i);
      notify();
      return i;
  }

  public synchronized int remove()  {
      while(pool.isEmpty()) {
          try {
              wait(1000);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
     int n = pool.removeFirst();
      notify();
      return n;
  }
}

  • 定义生产者
package com.thread;

public class Producer extends Thread {
    private static int index = 0;
    private String name;
    private ThreadPool pool;

    public Producer(String name, ThreadPool pool) {
        super();
        this.name = name;
        this.pool = pool;

    }

    @Override
    public void run() {

        while (true) {
            int num = pool.add(index++);
            System.out.println(this.name + " add: " + num);
        }
    }
}

  • 定义消费者
package com.thread;

public class Consumer extends Thread{
    private static int index = 0;
    private String name;
    private ThreadPool pool;

    public Consumer(String name, ThreadPool pool) {
        super();
        this.name = name;
        this.pool = pool;

    }

    @Override
    public void run() {

        while (true) {
            try {
                int num = pool.remove();
                System.out.println(name + " remove: " + num);
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

  • 启动类
package com.thread;

public class App {
    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool();
        Producer p1 = new Producer("p1", pool);
        Producer p2 = new Producer("p2", pool);


        Consumer c1 = new Consumer("c1", pool);
        Consumer c2 = new Consumer("c2", pool);

        p1.start();
        p2.start();

        c1.start();
        c2.start();



    }
}
总结

首先要注意当线程容量为1时,如果单纯地使用wait()方法,可能会出现死锁,笔者在这里写了相应的等待时间,当出现死锁的情况1s后就不等待了。当然也可以使用notifyAll()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值