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

解析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