线程同步锁的选择

在需要线程同步的时候如何选择合适的线程锁?

  例:选择可以存入到常量池当中的对象,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同步了,很是郁闷。

  我推荐选用的同步锁对象:

线程同步锁的选择
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数组充当同步锁对象,不会产生很诧异的错误同时不会占用很大内存。

作者:Orson 
出处:http://www.cnblogs.com/java-class/ 
如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】 
如果,您希望更容易地发现我的新博客,不妨点击一下左下角的【关注我】 
如果,您对我的博客内容感兴趣,请继续关注我的后续博客,我是【Orson】 

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段 声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 

转载:http://www.cnblogs.com/java-class/p/3145442.html

上一篇:Linux内核深入研究之进程的线性地址空间-传统版


下一篇:[Android Pro] ActionBarDrawerToggle 使用小结