多线程基础知识
多线程
生产者消费者模式
package com.mainwood.produceconsume;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author xuren
*/
public class PCDemo {
private Lock lock = new ReentrantLock();
private ArrayBlockingQueue queue = new ArrayBlockingQueue<>(10);
Condition condition = lock.newCondition();
private boolean flag = true;
private AtomicInteger atomicInteger = new AtomicInteger();
public void produce() {
lock.lock();
try {
while (flag) {
while (queue.size() != 0) {
System.out.println("队列已满,请等待。。。");
condition.await();
}
TimeUnit.SECONDS.sleep(1);
queue.offer(atomicInteger.incrementAndGet(), 5, TimeUnit.SECONDS);
System.out.println("放入第" + atomicInteger.get() + "个数据,剩余" + queue.size());
condition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void consume() {
lock.lock();
try {
while (flag) {
while (queue.size() == 0) {
System.out.println("-----队列空了,请等待。。。");
condition.await();
}
TimeUnit.SECONDS.sleep(1);
System.out.println("取出第" + queue.poll(5, TimeUnit.SECONDS) + "个数据,剩余" + queue.size());
condition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
class Test {
public static void main(String[] args) throws InterruptedException {
PCDemo pcDemo = new PCDemo();
new Thread(() -> {
pcDemo.produce();
}).start();
TimeUnit.MILLISECONDS.sleep(500);
new Thread(() -> {
pcDemo.consume();
}).start();
}
}
1、线程间的通信
public class DaYinDemo {
/**
* 0-A 1-B 2-C
*/
private int num = 0;
private Lock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
public void printA() {
lock.lock();
try {
while (num != 0) {
conditionA.await();
}
for (int i = 0; i < 5; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println("-------A---------");
}
num = 1;
conditionB.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
while (num != 1) {
conditionB.await();
}
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println("-------B---------");
}
num = 2;
conditionC.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
while (num != 2) {
conditionC.await();
}
for (int i = 0; i < 15; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println("-------C---------");
}
num = 0;
conditionA.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
class Test {
public static void main(String[] args) {
DaYinDemo daYinDemo = new DaYinDemo();
new Thread(() -> {
daYinDemo.printA();
}).start();
new Thread(() -> {
daYinDemo.printB();
}).start();
new Thread(() -> {
daYinDemo.printC();
}).start();
}
}
2、线程安全集合
- Vector
- Vector
public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
- Collections
List list = Collections.synchronizedList(new ArrayList<>()); public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); } public boolean add(E e) { synchronized (mutex) {return c.add(e);} }
- CopyOnWriteArrayList
List list = new CopyOnWriteArrayList(); public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
- HashTable
public synchronized V put(K key, V value) { }