我有一个对象A,我每秒更新一些数据,其他对象B和C每次更新只想使用一次数据。 每个对象并行工作。
如何让B和C等待A?
中的更新我看过一些类似的问题,但他们的回答并没有帮助我。 我已经看到我可以使用" synchronized"对象D上的集团,但他们只是放置集团而不告诉如何实例化或共享该对象。
以下代码是我用于测试的代码。我设法让他们并行工作,但我仍然坚持暂停部分。
这是A
的类public class Master{
public static void main(String[] args) throws Exception {
Worker B = new Worker("B");
B.start();
Worker C = new Worker("C");
C.start();
while(true)
{
Thread.sleep(1000);
// update data
// notify every thread waiting that they can resume
}
}
}
这是用于B和C的类
public class Worker extends Thread
{
Worker(String name)
{
super("Worker " + name);
}
public void run()
{
int i = 0;
while(!this.isInterrupted())
{
// wait for A to update data
System.out.println(i);
i++;
}
System.out.println("thread interrupted");
}
}
从那里开始,我需要为我寻找的目的添加什么?
答案 0 :(得分:1)
要做到非常低级别,只使用lang API,你应该使用wait / notifyAll。
不是我使用Main.class作为任意对象来同步
public class Main {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
Worker w1 = new Worker("Worker 1", sharedData);
Worker w2 = new Worker("Worker 2", sharedData);
w1.start();
w2.start();
while (true) {
try {
Thread.sleep(1000);
sharedData.increase();;
System.out.println("Master: " + sharedData.value());
synchronized (Main.class) {
Main.class.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class SharedData {
private int data = 0;
public void increase () {
data++;
}
public int value() {
return data;
}
}
class Worker extends Thread {
private String workerName;
private SharedData sharedData;
public Worker(String workerName, SharedData sharedData) {
super();
this.workerName = workerName;
this.sharedData = sharedData;
}
@Override
public void run() {
while (true) {
try {
synchronized (Main.class) {
Main.class.wait();
}
System.out.println(workerName + ": " + sharedData.value());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
答案 1 :(得分:0)
不确定我是否理解正确,但这可能值得一试: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
答案 2 :(得分:-2)
为什么要使用线程?为什么不这样做?
public class Master {
public static void main(String[] args) {
Worker B = new Worker("B");
Worker C = new Worker("C");
while(true) {
Thread.sleep(1000);
updateData();
B.doWork();
C.doWork();
}
}
}
public class Worker
{
public void doWork() {
System.out.println(i);
i++;
}
private int i = 0;
}