Resolve the Java thread synchronization lock selection method

  • 2020-04-01 01:51:24
  • OfStack

How to select the appropriate thread lock when thread synchronization is required?
Example: select objects that can be stored in the constant pool, String objects, etc


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:

public class MyThread1 extends Thread
{
    SyncTest syncTest;

    @Override
    public void run()
    {
        syncTest.method(this.getName());
    }
}

It was supposed to synchronize threads thread1 and thread2, and threads thread3 and thread4, but what happened?
Instead, threads thread1, thread2, thread3, and thread4 are synchronized, which is frustrating.
The synchronization lock object I recommend:

package com.rcx.thread;
public class SyncTest
{
    //A special instance variable that ACTS as an object for synchronization locks
    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();

    }
}

It is recommended to use a zero-length byte array as a synchronous lock object, which does not cause surprising errors and does not take up a lot of memory.


Related articles: