多线程
- 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()