As a multi-threaded Java development level of the Bible book, read the first pass tidy up the directory structure of the book knowledge, knowledge point for subsequent review and self-examination;
Context switching
When the CPU cycle time slice allocation algorithm executed by the task, the current will switch to the next task after task execution time slice, but before the switch will save the state before switching tasks for the next switch back to this task, this task can be loaded state, the task is to save the process of reloading a context switch.
Reducing context switching
- Lock-free concurrent programming
- CAS algorithm
- With a minimum thread
- Use coroutine - i.e., multi-task scheduling in a single thread.
Deadlock code sample
/**
* @author zhengzheng046
*/
public class DeadLockDemo {
private static String A = "A";
private static String B = "B";
public static void main(String[] args) {
new DeadLockDemo().deadLock();
}
private void deadLock() {
Thread t1 = new Thread(() -> {
synchronized (A) {
try {
System.out.println("当前线程名:" + Thread.currentThread().getName());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("1");
}
}
});
Thread t2 =new Thread(()->{
synchronized (B){
System.out.println("当前线程名:"+Thread.currentThread().getName());
synchronized (A){
System.out.println("2");
}
}
});
t1.start();
t2.start();
}
}