简体   繁体   English

单独的线程可以继续在另一个对象同步的对象上执行吗?

[英]Can a seperate thread continue execution on an object synchronised by another?

Say I have an object A which has 2 methods: 说我有一个对象A,它有2种方法:

public doSomething()
{....}

public synchronised doSomethingElse()
{ ... }

and I have thread1.doSomethingElse() , will it still be possible for thread2.doSomething() to execute or is it blocked by thread1's lock? 我有thread1.doSomethingElse()将它仍然有可能为thread2.doSomething()来执行,或者它阻止线程1的锁?

If so, how can I make thread1 execute at the same time? 如果是这样,如何使线程1同时执行?

There are two types of synchronization 1. Object level 2. Class level (Class level synchronization is for the static methods only.) 同步有两种类型:1.对象级别2.类级别(类级别同步仅适用于静态方法。)

In your case since your methods are not static it is object level synchronization. 在您的情况下,由于您的方法不是静态的,因此它是对象级同步。 For object level synchronization you can either synchronize your whole methods or you can synchronize some block of your methods. 对于对象级同步,您可以同步整个方法,也可以同步方法的某些块。

When you synchronized one method. 当您同步一种方法时。 Its mean that same object of your class cant access your synchronized method from different threads. 这意味着您的类的同一对象无法从不同的线程访问您的同步方法。 As each object have only one lock. 由于每个对象只有一个锁。 If you had called doSomethingElse() for same obj but from different threads. 如果您为相同的obj调用了doSomethingElse(),但来自不同的线程。 Then It will be accessible by one thread. 然后,将可以通过一个线程访问它。

Now comes to your answer: As your first method is not synchronized ie something(). 现在得出您的答案:由于您的第一个方法未同步,即something()。 It will not be effected in any case if you call it for any no of threads or even call it when your first thread is currently in the method. 如果您为任何线程数调用它,或者甚至在第一个线程当前在该方法中时调用它,则无论如何都不会生效。 Locks are only for synchronized methods 锁仅用于同步方法

Yourclass obj = new Yourclass();
Thread A = new MyThread(obj);
Thread B =  new MyThread(obj);

...... ......

public void run()
{
  \\do what ever you want
   \\both of your methods will be called.
   \\ call them both here.
}

here i have made objects of same Mythread class you can do as per you want. 在这里,我已经根据需要创建了与Mythread类相同的对象。 you can make objects of two different implemented thread classes and write your run. 您可以创建两个不同的已实现线程类的对象并编写运行。 In any case it will have no effect on the call. 在任何情况下,它都不会影响通话。

由于线程2不会尝试获取任何锁,因此它不会被阻塞并且可以与线程1并发运行。您无需执行任何特殊操作。

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

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