In this chapter we describe the synchronization with threadlocal on other objects.
In the previous section we used
1.synchronized Synchronizing on other objects
Class Threada implements Runnable {Private Object object = New Object ();p rivate synchronized void Test () throws Interrupte dexception {System.out.println ("dosomething"); Thread.Sleep, synchronized (object) {System.out.println ("dosomething");}} @Overridepublic void Run () {while (true) {try {test ()} catch (Interruptedexception e) {e.printstacktrace ();}}}}
2.ThreadLocal to eliminate synchronization issues with 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<integer> value = new Threadlocal<integer> () { 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 you can see that each thread is reading the value of the copy above the thread itself, and it modifies these without involving the original object.
Summary: This section briefly describes the synchronization and threadlocal of synchronized on other objects to eliminate the synchronization of shared objects.
This chapter is here, thank you.
-----------------------------------
Directory
Get to know java-18.6 from scratch synchronized synchronize and threadlocal on other objects to eliminate synchronization issues for shared objects