Preface: Three necessary conditions for thread safety are known: visibility, atomicity, and orderliness. Because some operations in ConcurrentHashMap are non-atomic, the final result does not match the expected result. For example:
1. Basic idea
1. Write a task class and implement multi-threading, rewrite the run method;
2. Write a static method to create a thread pool for multi-threaded calling and execution;
3. The final test is the result.
2. Code implementation
package FileTest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MutipulTrread {
public static void main(String args[])
{
int threadNum=1;
System.out.println("Single thread results:");
for (int i=0;i<5;i++)
{
System.out.println("Thet "+(i+1)+" Times Results:"+testAdd(threadNum));
}
System.out.println("The Multipul thread results:");
threadNum=5;
for (int i=0;i<5;i++)
{
System.out.println("Thet "+(i+1)+" Times Results:"+testAdd(threadNum));
}
}
static class TestTask implements Runnable
{
private ConcurrentHashMap<Integer,Integer>map;
public TestTask(ConcurrentHashMap<Integer,Integer> map)
{
this.map=map;
}
@Override
public void run() {
for (int i=0;i<100;i++)
{
map.put(1,map.get(1)+1);
}
}
}
private static int testAdd(int threadNum)
{
ConcurrentHashMap<Integer,Integer>map=new ConcurrentHashMap<>();
map.put(1,0);
ExecutorService pool= Executors.newCachedThreadPool();
for (int i=0;i<threadNum;i++)
{
pool.execute(new TestTask(map));
}
pool.shutdown();
try
{
pool.awaitTermination(20, TimeUnit.MICROSECONDS);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return map.get(1);
}
}
3. Results display
Single-threaded and multi-threaded results:
The result is not 500 every time, which shows that the thread is not safe
It's not easy to post, I implore the big guys to raise your hands!
Likes: Likes are a kind of virtue, and they are the recognition of my creation by the bosses!
Comments: There is no white contact, it is the beginning of communication between you and me!
Collection: May you pick more, it is the appreciation of the bosses to me!