当前位置:网站首页>Deadlock, thread communication, singleton mode
Deadlock, thread communication, singleton mode
2022-06-25 16:20:00 【weixin_ forty-eight million six hundred and forty-four thousand】
- Deadlock
- summary
Deadlock : Is in the process of execution , Both encountered the other party's method of locking , This leads to a state that everyone can't access
principle :
1 A particular thread Execution completed need successively nesting lock Execute two objects , And in the process , Lock the first object first
2 Another thread Execution completed need successively nesting lock Execute two objects , And in the process , Lock the second object first
3 When the first thread executes to the second object , Found locked , Can only wait for
4 When the second thread executes to the first object , Found locked , Can only wait for
- Code implementation
public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); Thread t1 = new Thread(new Thread_01(o1, o2)); Thread t2 = new Thread(new Thread_02(o1, o2)); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); } } class Thread_01 implements Runnable{ Object o1 ; Object o2; public Thread_01(Object o1, Object o2) { this.o1 = o1; this.o2 = o2; } @Override public void run() { synchronized (o1) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2) { System.out.println(Thread.currentThread().getName()+" Execution completed "); } } } } class Thread_02 implements Runnable{ Object o1 ; Object o2; public Thread_02(Object o1, Object o2) { this.o1 = o1; this.o2 = o2; } @Override public void run() { synchronized (o2) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o1) { System.out.println(Thread.currentThread().getName()+" Execution completed "); } } } }
- Thread communication
- summary
- wait : Put the thread into a waiting state , Locks held are released
No participation or introduction 0 To wait for , Will not wake up automatically , Can only wait notify Wake up it
Can also be passed in long Type value , Be similar to sleep, It's time to wake yourself up
notify : Randomly wake up a thread waiting in the object
notifyAll : Wake up all waiting threads in the object
The above methods can only be used in locked member methods ,
- Usage mode
- demand : Print odd and even numbers
1 There is a business class , There is a way to print odd numbers and even numbers
2 There is a variable count Record the current number
3 Two threads , Call the methods of printing odd and even numbers respectively public static void main(String[] args) { Num num = new Num(); Thread t1 = new PrintEven(num); Thread t2 = new PrintOdd(num); t1.setName("t1"); t2.setName("t2"); t2.start(); t1.start(); } } // Print even numbers class PrintEven extends Thread{ Num num; public PrintEven(Num num) { this.num = num; } @Override public void run() { while (true) { num.printEven(); } } } // Print odd numbers class PrintOdd extends Thread{ Num num; public PrintOdd(Num num) { this.num = num; } @Override public void run() { while (true) { num.printOdd(); } } } class Num{ int count =1 ; public synchronized void printOdd(){ System.out.println(Thread.currentThread().getName()+"--->"+count); count++; // Wake up other threads , To print even numbers this.notifyAll(); // Has reached the awaited try { Thread.sleep(500); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void printEven() { System.out.println(Thread.currentThread().getName() + "--->" + count); count++; // Wake up other threads , To print even numbers this.notifyAll(); // Has reached the awaited try { Thread.sleep(500); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
- producers and consumers
Message queue : producer / Consumer model _ Dongchen's blog -CSDN Blog _ Producer consumer model
Reduce coupling
package day_02;
import java.util.Random;
/**
* Similar to printing odd and even numbers , Use wait and notifyAll
*
* 1 A business class SynStack There's a variable , Used to save the number of produced elements
* 2 There is one in the business class char Array , Elements used to hold production ( If only produce a-z These letters )
* 3 There need to be two methods in the business class , One is production push , A consumer pop
* push Method It is mainly used to add data to the array
* Number to +1 , Also determine whether it is full , When it's full, hang up and wait
* pop Method It is mainly used to fetch the data in the array
* Number to -1 , But also to determine whether the consumption is over , When it's over, hang up and wait
* 4 Two threads , One is responsible for the production of , One is responsible for consumption
*/
public class Thread_03_ProduceConsumer {
public static void main(String[] args) {
SynStack ss = new SynStack();
Thread p = new Thread(new Producer(ss));
Thread c = new Thread(new Consumer(ss));
p.start();
c.start();
}
}
class Producer implements Runnable{
SynStack ss ;
public Producer(SynStack ss) {
super();
this.ss = ss;
}
@Override
public void run() {
Random random = new Random();
while (true) {
char ch = (char) (random.nextInt(26)+97);
ss.push(ch);
}
}
}
class Consumer implements Runnable{
SynStack ss ;
public Consumer(SynStack ss) {
super();
this.ss = ss;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
ss.pop();
}
}
}
class SynStack{
// Container for saving data
char[] data = new char[6];
// Number of production
int count = 0;
// production
public synchronized void push(char ch) {
// Judge whether it is full
if (count == data.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// That means it's not full , Started to produce
// Awaken consumers to prepare for consumption
this.notifyAll();
data[count ] = ch;
count++;
System.out.println(" Produced "+ch+" , The remaining "+count+" Elements ");
}
public synchronized char pop(){
// Determine whether it is null
if (count == 0) {
try {
// There's no need to wake up the producers here , Because the producer is full in wait, It's all empty , It means that the producer must not wait
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// This is not empty , Start spending
count--;
char ch = data[count];
// Wake up producers
this.notifyAll();
System.out.println(" The consumption "+ch+" , The remaining "+count+" Elements ");
return ch;
}
}
- The singleton pattern
Hungry man mode has no problem in a multithreaded environment , Because no matter how many threads Class can only be loaded once , So it will only be initialized once , This means that only one object can be created
package day_02;
/**
* The singleton pattern : Let a class instantiate only one object
*
* The constructor is privatized , Static variables hold objects , Public static methods are used to get class objects
*
* Hungry man mode has no problem in a multithreaded environment , Because no matter how many threads Class can only be loaded once , So it will only be initialized once , This means that only one object can be created
*/
public class Thread_05_SingLeton {
private Thread_05_SingLeton() {
}
/**
* volatile : Why use volatile Well ? Prevent command rearrangement
*
* https://www.cnblogs.com/dolphin0520/p/3920373.html
*
*/
private volatile static Thread_05_SingLeton singLeton = null;
// Low efficiency , Because you have to queue up every time
// public synchronized static Thread_05_SingLeton getInstance() {
// if (singLeton == null) {
// singLeton = new Thread_05_SingLeton();
// }
// return singLeton;
// }
// More efficient , Because you only need to queue for the first time
public static Thread_05_SingLeton getInstance() {
if (singLeton == null) {
synchronized (Thread_05_SingLeton.class) {
// 1// 2
if (singLeton == null) {
singLeton = new Thread_05_SingLeton();
}
}
}
return singLeton;
}
}
边栏推荐
- 商城风格也可以很多变,DIY 了解一下!
- 不要小看了积分商城,它的作用可以很大!
- Write one file to the marked location of another file
- Most commonly used SQL statements
- Vscode有什么好用的插件?
- 2021, committed to better development
- Several ways of SQL optimization
- Deep learning pytorch cifar10 dataset training "suggestions collection"
- 炮打司令部,别让一个UI框架把你毁了
- Reverse series to obtain any wechat applet code
猜你喜欢
Mixed density network (MDN) for multiple regression explanation and code example
Rxjs TakeUntil 操作符的学习笔记
Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
Gold three silver four, an article to solve the resume and interview
Advanced SQL statement 1 of Linux MySQL database
Navicat Premium 15 for Mac(数据库开发工具)中文版
What can one line of code do?
Understand the execution sequence of try catch finally in one diagram
《睡眠公式》:怎么治睡不好?
不要小看了积分商城,它的作用可以很大!
随机推荐
The database records are read through the system time under the Android system, causing the problem of incomplete Reading Records!
SQL最常用的语句
加载本地cifar10 数据集
Analysis of the concept of metacosmic system
cmd。。。。。。
User registration, information writing to file
揭秘GaussDB(for Redis):全面对比Codis
Leetcode topic [array]-34- find the first and last positions of elements in a sorted array
Report on Hezhou air32f103cbt6 development board
TensorFlow加载cifar10数据集
Uniapp converts graphic verification codes in the form of file streams into images
MT60B1G16HC-48B:A美光内存颗粒FBGA代码D8BNK[通俗易懂]
Don't underestimate the integral mall, its role can be great!
GridLayout evenly allocate space
Bugly hot update usage
f_ Read function [easy to understand]
Blue Bridge Cup - practice system login
Once the code was encrypted by the company's computer, the compilation failed
Vscode有什么好用的插件?
赫尔辛基交通安全改善项目部署Velodyne Lidar智能基础设施解决方案