Java Callables没有得到同步

时间:2017-10-08 22:34:30

标签: java java-7

我认为Java中的Synchronize方法一次只能执行一次。 但是,我看到如果2个callables正在通过同步块,它们将被并行执行。

这是我的具有固定Threadpool的Executor类。

public class ThreadExecutor 
{

    ExecutorService executors = Executors.newFixedThreadPool(100);
    public void callCallable2()
    {
        System.out.println("Inside executor callable 2 method");
        ThreadTestCallable2 t = new ThreadTestCallable2();
        executors.submit(t);
        System.out.println("Exiting executor callable 2 method");
    }

    public void callCallable1()
    {
        System.out.println("Inside the executor callable 1 method");
        ThreadTestCallable1 t = new ThreadTestCallable1();
        executors.submit(t);
        System.out.println("exiting the executor callable 1 method");
    }

}

我的可调用类是:

public class ThreadTestCallable1 implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Inside the threadtestcallable 1");
        ThreadHelperTest t = new ThreadHelperTest();
        t.test();
        System.out.println("Exiting the threadtestcallable 1");
        return null;
    }

}

public class ThreadTestCallable2 implements Callable{

    @Override
    public Object call() throws Exception {
        System.out.println("Inside the threadtestcallable 2");
        ThreadHelperTest t = new ThreadHelperTest();
        t.test();
        System.out.println("exitting the threadtestcallable 2");
        return null;
    }


}

我的callable synchronize方法在helper类中。

public class ThreadHelperTest 
{
    public void test()
    {
        test1();
    }

    public synchronized void test1()
    {
        try {
            System.out.println("Sleeping for 10 sec's T-name: "+ 
            Thread.currentThread().getName());
            Thread.sleep(60000);
            System.out.println("wokeup T-Name: "+ 
            Thread.currentThread().getName());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

这是我的主要课程:

public class ThreadTest {

    public static void main(String arg[]){

        ThreadExecutor t = new ThreadExecutor();
        t.callCallable1();
        t.callCallable2();
    }

}

上面执行的最终输出是我看到两个callables一次进入同步方法,这不应该发生,Monitor对象有什么问题。?

请查看上述代码的结果:

Inside the executor callable 1 method
exiting the executor callable 1 method
Inside executor callable 2 method
Inside the threadtestcallable 1
Exiting executor callable 2 method
Inside the threadtestcallable 2
Sleeping for 10 sec's T-name: pool-1-thread-1
Sleeping for 10 sec's T-name: pool-1-thread-2
wokeup T-Name: pool-1-thread-1
Exiting the threadtestcallable 1
wokeup T-Name: pool-1-thread-2
exitting the threadtestcallable 2

如果有任何需要改变,请建议我。 让这些方法同步。

1 个答案:

答案 0 :(得分:0)

您的每个callables都有自己的ThreadHelperTest实例。允许对不同实例的synchronized method的呼叫进行交错。

  

首先,同一个对象上的两个同步方法的调用不可能交错。

您可以将ThreadHelperTest的同一个实例传递给您的callables,或使用其他任何共享的互斥锁进行同步。