在需要線程同步的時候如何選擇合適的線程鎖?
例:選擇可以存入到常量池當中的對象,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數組充當同步鎖對象,不會產生很詫異的錯誤同時不會占用很大內存。