A wonderful multi-threaded synchronization case

xiaoxiao2021-03-06  66

Import java.util.treemap; / ** * This program demonstrates how small particle size locks using TreeMap. * * Multiple threads need to find and modify the same shared object from a TreeMap from a TreeMap. Initially, these shared objects do not exist in TreeMap; * Each thread that finds it does not exist will call the loadFromDatabase () method to create a new object and put the result into TreeMap. * Execute this method will take 1000ms. * * After finding success from TreeMap, each thread will attach your own name to the back of this object and print the object. Therefore, the performance of the printing shows the modification order of each thread. * * Program utilizes TreeMap's characteristics to ensure that for each shared object, LoadFromDatabase () is executed once and only once. At the same time, it does * guaranteed a dead lock, and it is possible to avoid unnecessary blocking between different shared objects. In this program, although each shared object requires a lookup time of 1000 ms *, the total lookup time does not change significantly with the number of shared objects of the lookup. * * The reader can try to use long instead of synclong, or in other ways to implement problems such as performance and stability in the multi-threaded programming environment. * / Public class Demo {static long beginFind, lastFind; static TreeMap sharedResourceMap = new TreeMap (); static int i; static class SyncLong implements Comparable {long value; public SyncLong (long value) {this.value = value;} public void Block () {// try to lock myself Here // System.out.println ("Lock Myself" System.currentTimeMillis ()); Synchronized (this) {// system.out.println ("Unlock Myseelf" System .currenttimemillis ());}} public int compareto (Object obj) {long Anotherval = ((synclong) obj) .value; if (synclong) (synclong) obj) .block (); return (Value

转载请注明原文地址:https://www.9cbs.com/read-89766.html

New Post(0)