concurrent parallelism
Concurrency: Multiple threads operate the same resource
Parallelism: multiple threads can execute simultaneously (CPU must be multi-core)
The essence of concurrent programming: making full use of CPU resources (more important to the company)
//获取CPU的核数
System.out.println(Runtime.getRuntime().availableProcessors());
6 states of threads
1. New (initial): Thread rebirth
2. Runnable: running status
3. Blocked: blocked
4. Waiting: Waiting is a kind of blocking
5. Time_waiting: timeout waiting
6. Terminated: terminated
The difference between wait and sleep
- from different classes
wait->Object
sleep->Thread
- About lock release
wait will release the lock, sleep will sleep, and sleep holding the lock, it will not release it.
- The scope of use is different
wait must be in the synchronization code block, sleep can be anywhere
lock lock
if there will be a false wake-up problem
public class Test3 {
public static void main(String[] args) {
Data data = new Data();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.addNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.deNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.deNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.deNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "D").start();
}
}
//判断等待-业务计算-通知
class Data {
private int num=0;
public synchronized void addNumber() throws InterruptedException {
while(num!=0){
//防止虚假唤醒
this.wait();//等待
}
num++;
System.out.println(Thread.currentThread().getName()+"->"+num);
this.notifyAll();//通知
}
public synchronized void deNumber() throws InterruptedException {
while(num==0){
this.wait();//等待
}
num--;
System.out.println(Thread.currentThread().getName()+"->"+num);
this.notifyAll();//通知
}
}
Traditional: 1.synchronized, 2.wait, 3.notifyAll wakes up all
Now: 1.lock, condition (2.await wait, 3.signalAll wakes up all)
condition can achieve precise notification wake-up
condition.await();
condition2.sigal();
8 lock phenomenon
Collection class is not safe
ArrayList is safe when single-threaded, but not safe when concurrently
// List<String> list=new Vector<>();
List<String> list=new ArrayList<>();
List<String> list1= Collections.synchronizedList(new ArrayList<>());//可以变安全
List<String> list2= new CopyOnWriteArrayList<>();//并发时安全,写入时复制,DOW计算机程序设计的一种优化策略,比vector(有synlized效率都低)效率高
set is unsafe:
// Set<String> set = new HashSet<>();
Set<String> set1 = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet();//和list一样
Map is not safe
Map<String, String> map = new HashMap();//加载因子(0.75),初始容量(16)
Map<String, String> map1 = Collections.synchronizedMap(new HashMap<>());
Map<String, String> map2 =new ConcurrentHashMap<>();//并发的hashmap这个和ArrayList,HashSet不一样
callable
- Compared with the other two, there can be a return value;
- Can throw exceptions;
- The methods are different, run and call.
MyThread myThread=new MyThread();
//适配类
FutureTask futureTask=new FutureTask(myThread);//FutureTask是个中间商,可以吧Callable和Runnable连接起来
new Thread(futureTask,"A").start();
Integer o= (Integer) futureTask.get();//获取Callable的返回值
/*
*new Thread(futureTask,"A").start();
*new Thread(futureTask,"B").start();//会打印一个call,结果会被缓存,提高效率,
*1.有缓存
*2.结果需要等待
*/
Commonly used auxiliary classes
1. CountDownLatch
数量减一,计数器归零,await等待结束,会被唤醒
countDownLatch.countDown();//数量减一
countDownLatch.await();//等待计数器归零,计数器变为0,await结束等待
2. CyclicBarrier
cyclicBarrier.await();//会进行计数,数量+1,计数后会开启新的线程执行
3.Semaphore//适用于停车位,限流
Semaphore semaphore=new Semaphore(6);//默认线程数量
semaphore.acquire();//得到资源,如果已经满了,需要等待
TimeUnit.SECONDS.sleep(2);
semaphore.release();//释放资源,当前的信号释放量+1,唤醒等待的资源
read-write lock
ReadWriteLock readWriteLock= new ReentrantReadWriteLock();
readWriteLock.writeLock().lock();
readWriteLock.writeLock().unlock();