How do I select a proper thread lock when thread synchronization is required?
For example, select an object or String object that can be saved to the constant pool.
Copy codeThe Code is as follows: public class SyncTest
{
Private String name = "name ";
Public void method (String flag)
{
Synchronized (name)
{
System. out. println (flag + ", invoke method ....");
Try
{
Thread. sleep (1000 );
}
Catch (InterruptedException e)
{
E. printStackTrace ();
}
}
}
Public static void main (String [] args)
{
SyncTest test1 = new SyncTest ();
SyncTest test2 = new SyncTest ();
MyThread1 myThread1 = new MyThread1 ();
MyThread1 myThread2 = new MyThread1 ();
MyThread1.syncTest = test1;
MyThread2.syncTest = test1;
MyThread1 myThread3 = new MyThread1 ();
MyThread1 myThread4 = new MyThread1 ();
MyThread3.syncTest = test2;
MyThread4.syncTest = test2;
MyThread1.start ();
MyThread2.start ();
MyThread3.start ();
MyThread4.start ();
}
}
Thread class:Copy codeThe Code is as follows: public class MyThread1 extends Thread
{
SyncTest syncTest;
@ Override
Public void run ()
{
SyncTest. method (this. getName ());
}
}
We should have implemented synchronization between thread1 and thread2, and synchronization between thread3 and thread4. What is the result?
It makes the threads thread1, thread2, thread3, and thread4 synchronize, and it is very depressing.
The synchronization lock objects I recommend:Copy codeThe Code is as follows: package com. rcx. thread;
Public class SyncTest
{
// Special instance variable, used to act as the synchronization Lock Object
Private byte [] lock = new byte [0];
Public void method (String flag)
{
Synchronized (lock)
{
System. out. println (flag + ", invoke method f ....");
Try
{
Thread. sleep (1000 );
}
Catch (InterruptedException e)
{
E. printStackTrace ();
}
}
}
Public static void main (String [] args)
{
SyncTest test1 = new SyncTest ();
SyncTest test2 = new SyncTest ();
MyThread1 myThread1 = new MyThread1 ();
MyThread1 myThread2 = new MyThread1 ();
MyThread1.syncTest = test1;
MyThread2.syncTest = test1;
MyThread1 myThread3 = new MyThread1 ();
MyThread1 myThread4 = new MyThread1 ();
MyThread3.syncTest = test2;
MyThread4.syncTest = test2;
MyThread1.start ();
MyThread2.start ();
MyThread3.start ();
MyThread4.start ();
}
}
We recommend that you use a byte array with a length of 0 to act as the synchronization Lock Object. This will not cause any surprising errors and will not occupy a large amount of memory.