Java-18.6 synchronized synchronization and ThreadLocal on other objects from the ground up to eliminate the synchronization problem of shared objects
This section describes synchronization and ThreadLocal on other objects.
In the previous chapter, we used
1. synchronized synchronization on other objects
class ThreadA implements Runnable {private Object object = new Object();private synchronized void test() throws InterruptedException {System.out.println("dosomething");Thread.sleep(5000);synchronized (object) {System.out.println("dosomething");}}@Overridepublic void run() {while (true) {try {test();} catch (InterruptedException e) {e.printStackTrace();}}}}
2. ThreadLocal to eliminate synchronization of shared objects
package com.ray.ch18;public class Test {public static void main(String[] args) {new Thread(new Accessor(new ThreadLocalVarHoder())).start();new Thread(new Accessor(new ThreadLocalVarHoder())).start();new Thread(new Accessor(new ThreadLocalVarHoder())).start();}}class Accessor implements Runnable {private ThreadLocalVarHoder threadLocalVarHoder;public Accessor(ThreadLocalVarHoder threadLocalVarHoder) {this.threadLocalVarHoder = threadLocalVarHoder;}@Overridepublic void run() {for (int i = 0; i < 3; i++) {threadLocalVarHoder.increment();System.out.println(Thread.currentThread().getName() + " "+ threadLocalVarHoder.get());}}}class ThreadLocalVarHoder {private static ThreadLocal
value = new ThreadLocal
() {protected Integer initialValue() {return 0;}};public void increment() {value.set(value.get() + 1);}public int get() {return value.get();}}
Output:
Thread-0 1
Thread-0 2
Thread-0 3
Thread-1 1
Thread-2 1
Thread-2 2
Thread-2 3
Thread-1 2
Thread-1 3
From the above output, we can see that each thread reads the value of the copy on its own thread, and its modifications do not involve the original objects.
Summary: This section briefly introduces synchronized synchronization and ThreadLocal on other objects to eliminate the synchronization problem of shared objects.