为什么我的代码中没有获得同步访问权限?

时间:2017-05-03 19:40:28

标签: java synchronization

class Caller extends Thread
{


    String s;



    Caller(String s)
    {

        this.s=s;
    }


    void call(String msg)
    {
        synchronized (this)
        {
            System.out.print("["+msg);

            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
            System.out.println("]");
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

    }   

    public void run()
    {


        call(s);
    }

}


public class SynchronisedBlock {

    public static void main(String[] args) {


        Caller c=new Caller("hi");
        Caller c1=new Caller("li");
        Caller c2=new Caller("wi");

        c.start();
        c1.start();
        c2.start();


    }

}


    public class SynchronisedBlock {

        public static void main(String[] args) {


            Caller c=new Caller("hi");
            Caller c1=new Caller("li");
            Caller c2=new Caller("wi");

            c.start();
            c1.start();
            c2.start();


        }

    }

我正在尝试使用synchronized块获取对call()的同步访问但没有获得该功能。当我将call()方法放在另一个类中时,我获得了所需的功能但不在此代码中。我错过了什么?谁能告诉我为什么?提前完成。

2 个答案:

答案 0 :(得分:0)

正如@svasa所说,你需要有一个共同的同步对象。 代码最简单的工作示例是使用共享的lock对象。此外,lockfinal以防止它被代码中的其他位置替换,您最终会在不同对象上进行同步。 (感谢@ P.J.Meisch):

class Caller extends Thread {

    String s;
    private static final Object lock = new Object();

    Caller(String s) {

        this.s = s;
    }

    void call(String msg) {
        synchronized (lock) {
            System.out.print("[" + msg);

            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println("]");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }

    }

    public void run() {

        call(s);
    }

答案 1 :(得分:0)

如果您的run方法与Runnable类似,而不是Thread,那么您可以传递相同的Runnable实例每个线程和this将作为同步对象引用。

相关问题