java 为什么接口中不包含同步方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14520814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:31:51  来源:igfitidea点击:

Why synchronized method is not included in interface

javamultithreadingoop

提问by devsda

When I use synchronizedon a method in an interface, the compiler emits an error. Can you tell me why this happens?

当我synchronized在接口中的方法上使用时,编译器会发出错误。你能告诉我为什么会这样吗?

What is the reason (logically) that synchronizedcannot be applied to a method on an interface?

synchronized不能应用于interface?上的方法的原因(逻辑上)是什么?

I tried to make an Interface over Threadpool in this link. Help me to make Interface in my above code.

我试图在此链接中通过 Threadpool 创建一个接口。帮我在上面的代码中制作接口。

回答by JB Nizet

Because synchronizedis an implementation detail. One implementation of the method might need to make the method synchronized, whereas another one might not need it. The caller doesn't care whether the method is synchronized or not. It's not part of the contract, which tells whatthe method does. Which synchronization technique, if any, is used to fulfill the contract is irrelevant.

因为synchronized是一个实现细节。方法的一种实现可能需要使方法同步,而另一种实现可能不需要它。调用者并不关心该方法是否同步。它不是合同的一部分,它说明该方法的作用。使用哪种同步技术(如果有)来履行合同是无关紧要的。

回答by Jilles van Gurp

synchronized is an implementation detail and doesn't belong in an interface.

synchronized 是一个实现细节,不属于接口。

You could have all sorts of implementations that might be threadsafe that don't involve the use of the keyword synchronized.

您可以拥有各种不涉及使用关键字 synchronized 的线程安全实现。

You might consider using some annotation to indicate the intention that implementations should be thread safe. For example http://jetbrains.dzone.com/tips/concurrency-hot-try-jcipexplains how to use the JCIP concurrency annotations.

您可能会考虑使用一些注释来表明实现应该是线程安全的意图。例如http://jetbrains.dzone.com/tips/concurrency-hot-try-jcip解释了如何使用 JCIP 并发注释。

BTW. Instead of using synchronized, you may want to get cozy with the java concurrent framework. Using low level constructs like synchronized directly is considered a bit of an anti pattern these days.

顺便提一句。您可能想要熟悉 Java 并发框架,而不是使用同步。如今,直接使用诸如同步之类的低级构造被认为有点反模式。

回答by user3674202

The simple answer is synchronized is talking about method implementation, but in interface all methods are abstract that means no implementation.

简单的答案是同步正在谈论方法实现,但在接口中所有方法都是抽象的,这意味着没有实现。