程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> 解析Java線程同步鎖的選擇方法

解析Java線程同步鎖的選擇方法

編輯:JAVA編程入門知識

在需要線程同步的時候如何選擇合適的線程鎖?
例:選擇可以存入到常量池當中的對象,String對象等  
代碼如下:

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();

    }

}

線程類:
代碼如下:

public class MyThread1 extends Thread
{
    SyncTest syncTest;

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

本來應該是要實現線程thread1和thread2同步,線程thread3和thread4同步的,但結果呢?
卻是使得線程thread1、thread2、thread3、thread4同步了,很是郁悶。
我推薦選用的同步鎖對象:
代碼如下:

package com.rcx.thread;

public class SyncTest
{
    // 特殊的instance變量,用於充當同步鎖的對象
    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();

    }

}

推薦使用0長度的byte數組充當同步鎖對象,不會產生很詫異的錯誤同時不會占用很大內存。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved