简体   繁体   English

Java中的线程说明

[英]Thread clarification in Java

Is it possible to synchronize the method when we extend Thread rather than implementing Runnable ? 当我们扩展Thread而不是实现Runnable时是否可以同步该方法?

I know that when we use Runnable , it is possible. 我知道当我们使用Runnable ,这是可能的。 But when we do Thread t1 = new Thread(); 但是当我们执行Thread t1 = new Thread(); , can this be done? ,可以这样做吗?

How can it be synchronized? 如何同步?

Synchronization is orthogonal to the class on which the method is defined. 同步与定义该方法的类正交。 You can use synchronized in any method. 您可以通过任何方法使用synchronized It just means there's a mutex guarding that block of code. 这只是意味着有一个互斥体来保护该代码块。

public class MyTotallyUnspecialClass {
    synchronized public void someTotallyUnspecialMethod() {
        // this method is synchronized, with a mutex on "this"
    }
}

There is no effect on synchronization whether you extend Thread or implement Runnable. 扩展线程还是实现Runnable对同步都没有影响。 When you synchronize a method , you get a lock on the OBJECT and not the thread - so it really does not matter.There are many SO topics that discuss the distinction between these 2 approaches (extending thread vs implementing Runnable) 当同步一个方法时,您获得的是对象而不是线程的锁,所以这实际上没关系。有很多SO主题讨论了这两种方法之间的区别(扩展线程与实现Runnable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM