当前位置:网站首页>Solving multithreading security problems
Solving multithreading security problems
2022-06-12 15:18:00 【A_ M amu】
1. review
1. Threads ?
(1) What process And what thread ?
(2) Why multithreading .
(3) How to implement multithreading ?【1】 Inherit Thread 【2】 Realization Runnable Interface 【3】 Realization Callable Interface
(4)Thread Common methods in thread classes .
1. static void sleep(long n): Thread to sleep
2. void join(): Join the current thread , Make the current thread wait for the added thread to finish executing .
3. yield(): Make the thread abandon the current time slice , Enter the pending queue again , Compete with other threads for time slices .
4. priority(): set priority
5. setDaemon(): Set to daemons
6. Thread.currentThread().getName(): Get the name of the current thread
(5) Thread safety problem :
1. Premise : [1] Multithreading [2] Shared resources .
2. This chapter
1. Solving thread safety problems .
2. Deadlock and how to avoid it .
3. Thread communication
4. Thread pool .
5. Use callable Complete multithreaded tasks .
3. Solving thread safety problems .-- Lock
(1)synchronized---- Automatic lock
package demo04;
import java.util.Arrays;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:57
**/
public class TestSafy {
private static String[] arr=new String[5];
private static int index=0;
public static void main(String[] args) throws Exception {
// Create a task to put hello
Runnable tast01=new Runnable() { // Anonymous inner class
@Override
public void run() {
synchronized (arr) { //() Lock resource ----- Share resources as lock resources . As long as the same lock resource is used, it can be locked successfully .
if (arr[index] == null) { // time out
arr[index] = "hello";
index++;
}
}
}
};
Runnable tast02=new Runnable() { // Anonymous inner class
@Override
public void run() {
synchronized (arr) {
if (arr[index] == null) {
arr[index] = "world";// time out
index++;
}
}
}
};
Thread t1=new Thread(tast01," Threads A");
Thread t2=new Thread(tast02," Threads B");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(Arrays.toString(arr)); // Belong to main
}
}package demo04;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 10:34
**/
public class TestTicket {
public static void main(String[] args) {
Ticket task=new Ticket();// Task object
Thread t1=new Thread(task," window A");
Thread t2=new Thread(task," window B");
Thread t3=new Thread(task," window C");
Thread t4=new Thread(task," window D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable {
private Integer ticket = 100;
private Object o=new Object(); // Create a new one Object As a lock resource
@Override
public void run() {
while (true) {
synchronized (this) { //() What you want is an object ! tiket It's a int type
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " Sold one , The remaining :" + ticket + " Zhang ");
}
}
}
}(2)lock------ Manual lock .
package demo04;
import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 11:57
**/
public class TestSafy {
private static String[] arr=new String[5];
private static int index=0;
public static void main(String[] args) throws Exception {
final Lock lock=new ReentrantLock();// Reentrant lock : It can be locked many times . Create a manual lock object
// Create a task to put hello
Runnable tast01=new Runnable() { // Anonymous inner class
@Override
public void run() {
try {
lock.lock();// locked
if (arr[index] == null) { // time out
arr[index] = "hello";
index++;
}
}finally {
lock.unlock();// Unlock
}
}
};
Runnable tast02=new Runnable() { // Anonymous inner class
@Override
public void run() {
try {
lock.lock();
if (arr[index] == null) {
arr[index] = "world";// time out
index++;
}
}finally {
lock.unlock();
}
}
};
Thread t1=new Thread(tast01," Threads A");
Thread t2=new Thread(tast02," Threads B");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(Arrays.toString(arr)); // Belong to main
}
}package demo04;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program: Thread01
* @description:
* @author: Amur
* @create: 2022-01-04 10:34
**/
public class TestTicket {
public static void main(String[] args) {
Ticket task=new Ticket();// Task object
Thread t1=new Thread(task," window A");
Thread t2=new Thread(task," window B");
Thread t3=new Thread(task," window C");
Thread t4=new Thread(task," window D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable {
private Lock lock=new ReentrantLock();
private Integer ticket = 100;
private Object o=new Object(); // Create a new one Object As a lock resource
@Override
public void run() {
while (true) {
try{
lock.lock();
if (ticket <= 0) {
break;
}
ticket--;
System.out.println(Thread.currentThread().getName() + " Sold one , The remaining :" + ticket + " Zhang ");
}finally {
lock.unlock();
}
}
}
}HashMap and HashTable The difference between ?
HashMap: allow key and value by null,hashmap Thread unsafe , But it's efficient . HashTable: Don't allow key and value by null, It's thread safe , Low efficiency .
HashMap How to realize the bottom layer of ?
1、 Array + Linked list + Red and black binary tree . hashMap The stored call is put(key,value), according to key Of hash Value to determine whether there are elements with the same hash value in the array , If not, it will be stored in the array , If there are elements with the same hash value , Hash conflicts are considered , Compare their equals Are they the same? , If the same , It is considered to be the same element , Replace the original key Corresponding value value . If different , Then it is stored in the linked list , If the hash conflicts with too many elements (8), Then it is stored in the red black binary tree .
ArrayList and LinkedList The difference between !
1. ArrayList: The bottom layer is array structure , It's a continuous memory space , Suitable for query operation , Not insert and delete , Because insert and delete , It involves data migration . 2. LinkedList: The bottom layer is linked list structure , Suitable for insertion and insertion operation , Not suitable for lookup operations .
String,StringBuffer and StringBuilder The difference between
1. String Bottom use final modification . Its value cannot be changed , Regenerate the reference address every time you change . 2. StringBuffer and StringBuilder Its value can be changed , Use append Add . 3. StringBuffer Thread safety , But it's inefficient , It is recommended to use in multithreading . 4. StringBuilder Thread unsafe , But it's efficient , It is recommended to use in single thread .
Deadlock and how to avoid it .
How to avoid :
1. Try not to use lock nesting .
2. Try to use security classes .
3. Sure lock The lock tryLock Set the lock time .
边栏推荐
- TF learning notes in ROS
- Servlet连接数据库实现用户登录功能
- Deepin20.6 rtx3080 installing graphics card drivers 510.60.02, cuda11.6, pytorch1.11
- 安装rhel 7/8 (红帽)虚拟机(转载)
- [SPARK][CORE] 面试问题之什么是 external shuffle service?
- 简单的爬虫框架:解析51job页面岗位信息
- Leetcode daily question - fair candy bar exchange
- About layoffs in Internet companies
- How to set public IP access on the H3C gr5200 router
- Selenium advanced
猜你喜欢

Structure example

虚拟机中用户和root忘记密码解决办法

Simple crawler framework: parsing 51job page position information

ngork实现内网穿透--免费

C operator

TCP与UDP的区别,以及TCP的三次握手和TCP的四次挥手

PTA:自测-3 数组元素循环右移问题 (20分)

Jetpack architecture component learning (3) -- activity results API usage

Kinect2.0+ORBSLAM2_with_pointcloud_map

Selenium advanced
随机推荐
3D reconstruction system | L3 incremental motion recovery structure (incremental SFM)
Array related content
First set and follow set in vernacular
USART (rs232422485), I2C, SPI, can, USB bus
[game server design cases] insights
vim的安装以及常用命令
Understanding of Odom coordinate system
PHPstudy建站提示hosts文件可能不存在或被阻止打开,同步hosts失败怎么解决
分布式并发重复提交问题
h3c GR5200路由器上如何设置公网ip可以访问
ARM 64指令小记
安装PS软件时提示程序无法访问关键文件/目录,错误代码:41的解决方法
The process of generating strong association rules from frequent itemsets
Qiming cloud sharing | demonstrate the switch through an example of the matter protocol to control the light on and off through the matter protocol
[spark][core] what is an external shuffle service?
Alibaba, Tencent et pingduo sont à la recherche d'une nouvelle logique pour l'Internet industriel
Solve log4j2 vulnerability and be attacked by mining and zombie process viruses
Open Chinese path file in C language
Browser fingerprint interpretation
New关键字、引用&与指针的学习记录