当前位置: 移动技术网 > IT编程>开发语言>Java > 解析Java线程同步锁的选择方法

解析Java线程同步锁的选择方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

在需要线程同步的时候如何选择合适的线程锁?
例:选择可以存入到常量池当中的对象,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数组充当同步锁对象,不会产生很诧异的错误同时不会占用很大内存。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网