[英]Sharing Condition and Lock variable Across Classes in Java
I want to write a program where two separate threads run two objects and one thread waits to execute its code till it is signalled by the other.我想编写一个程序,其中两个单独的线程运行两个对象,一个线程等待执行其代码,直到另一个线程发出信号。
Now to do this I want to use the Condition
interface.现在要做到这一点,我想使用
Condition
接口。
I am unable to figure out where to declare the lock
and condition
variables in my code such that both classes have access to it.我无法弄清楚在我的代码中在哪里声明
lock
和condition
变量,以便两个类都可以访问它。
What I want to ask is, how do threads share the lock
and condition
variables so that it is ensured that they are signalling and waiting on the same condition.我想问的是,线程如何共享
lock
和condition
变量,以确保它们在相同的条件下发出信号和等待。
The threads will have to have some sort of connection for this to work.线程必须有某种连接才能工作。 If thread 1 has a reference to thread 2, the lock and condition variables may be in thread 2 and vice versa.
如果线程 1 引用了线程 2,则锁和条件变量可能在线程 2 中,反之亦然。
If not, the variables will have to be in a separate class which both threads have access to.如果不是,则变量必须位于两个线程都可以访问的单独类中。 So, you'll have to pass the same instance of that class to both threads, so that instance becomes a shared resource.
因此,您必须将该类的相同实例传递给两个线程,以便该实例成为共享资源。 Following example assumes you have classes
Thread1
and Thread2
that extends Thread with a constructor taking SharedResource
as an argument:以下示例假设您有类
Thread1
和Thread2
与构造以继承Thread SharedResource
作为参数:
SharedResource sr = new SharedResource();
Thread1 t1 = new Thread1(sr);
Thread2 t2 = new Thread2(sr);
t1.start();
t2.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.