解析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數組充任同步鎖對象,不會發生很驚訝的毛病同時不會占用很年夜內存。