review
In the last article on Multithreaded programming in Java basics, we explained the implementation of multithreading, which seems to work fine, but if we add a piece of code
Class Window implements Runnable{// implement interface int ticket=100; @Override public voidrun() {
while (true) {if(ticket>0){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Ticket number: :"+ ticket--);
}else{
break;
}
}
}
}
Window w=new Window();
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
t1.setName("Window 1");
t2.setName("Window 2");
t1.start();
t2.start();
Copy the code
Compared to the code in the last article
Thread.currentThread().sleep(10);
Copy the code
The sleep() method causes the current thread to block for 10 milliseconds
This is where thread insecurity exists
Problem analysis
So how do we analyze this phenomenon? Let’s assume that there are two threads selling tickets: thread A and thread B, and there is one ticket left
When ticket=1, thread A enters the if judgment, then thread A enters the sleep state, and then thread B obtains CPU execution rights and starts executing. When ticket=1, thread A enters the if judgment and starts to sleep, and then thread A’s sleep stops and starts executing. Ticket –, ticket=0, and thread B resumes, printing tickect 0, ticket -1 again. This is when three Windows sell tickets at the same time, the reason for the overselling, also known as thread insecurity.
Thread safety
What are the causes of thread insecurity? So what’s the solution?
- We want one thread to share data before other threads have a chance to share data.
Thread safety is a concept in computer program code in multithreaded programming. In the parallel execution of programs with multiple threads with shared data, thread-safe code ensures that each thread can execute normally and correctly through the synchronization mechanism without data contamination and other unexpected situations.
There are two main ways to implement Java code:
Synchronization mechanism for threads
Method one: Synchronize code blocks
The format is as follows use the synchronized keyword
Synchronized {// Blocks of code that need to be synchronized(blocks that operate on shared data)}Copy the code
The synchronization monitor above is also called “lock”, the lock needs to be unique, the code is as follows
Class Window implements Runnable{// implement interface int ticket=100; @Override public voidrun() {
while (true){
synchronized (this){
if(ticket>0){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Ticket number: :"+ ticket--);
}
}
}
}
}
Copy the code
The command output is as follows: Normal!
Method two: Synchronous method
Extract the code that operates on shared data into a method and modify it with synchronized
synchronized void show(){// Code to manipulate shared data}Copy the code
Modify the ticketing program with synchronous method as follows:
Class Window implements Runnable{// implement interface int ticket=100; public synchronized voidshow() {if(ticket>0){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Ticket number: :"+ ticket--);
}
}
@Override
public void run() {
while (true){ this.show(); }}}Copy the code
Note that the lock defaults to this and also needs to be unique in a synchronized implementation. Let’s illustrate how two threads operate on shared data in thread safety:
As we know from the figure above, threads always execute synchronously whenever an operation shares data.
conclusion
- Thread insecurity occurs when multiple threads operate on shared data
- Synchronized methods or blocks of synchronized code are used to make threads execute synchronously
- Both synchronized methods and synchronized code blocks require an object as a lock that is guaranteed to be unique
If you like this article, please click on the subscription number “My Programming Notes” for more content