gpt4 book ai didi

java:将类引用传递给另一个线程

转载 作者:行者123 更新时间:2023-12-01 23:41:09 25 4
gpt4 key购买 nike

我正在尝试学习如何在 Java 中使用多线程。我有一个 main 和两个扩展 Thread 的类,A 和 B。我希望 main 启动 A,这会多次调用 B。A 完成后,我希望 B 向 main 发送一些内容。

main创建两个线程,一个A,一个B,然后启动这两个线程。 A 做了一些事情,然后将结果传递给 B。然后 main 收集 B 的答案并做其他事情。我不知道如何将 B 中的总数返回到 main 中。

我也不确定如何实例化这两个类(线程),但然后给 A 一个 B 的引用,因为 Java 使用按值传递。有人可以给我一些指点吗?

public static void main(String[] args)
{
B b = new B();
A a = new A(100, b);

B.start();
A.start();

A.join(); // Waiting for A to die

// Here I want to get a total from B, but I'm not sure how to go about doing that

}


public class A extends Thread
{
private int start;
// Some reference to B
B b;
public A (int n, B b) {
int start = n;
this.b = b;
}

public void run() {
for (int i = 0; i < n; i++) {
b.add(i);
}
}
}

public class B extends Thread
{
private int total;

public B () {
total = 0;
}

public void add(int i) {
total += i;
}
}

最佳答案

我将您的示例代码更改为我认为更有意义的示例。

线程之间的通信通常通过共享数据(或管道、套接字等 channel - 但我不会去那里......)来处理。虽然将共享数据包含在线程类中是完全可以的,但我已将共享数据与用于管理线程的数据/方法分开。

希望这可以帮助您理解线程和数据对象之间的关系。

public class TestThreads {
public static void main(String[] args)
{
DataShare ds = new DataShare();
B b = new B(ds);
A a = new A(100, ds);

b.start();
a.start();

try {
a.join(); // Waiting for A to die
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println ("Accumulated total from B = " + b.getTotal());
b.endThread();
}
}


public class DataShare {
private int value;

public DataShare () {
value = -1;
}

public synchronized boolean setValue(int val) {
boolean valueSet = false;
if (value == -1) {
value = val;
valueSet = true;
}
return valueSet;
}

public synchronized int getValue() {
int val = value;
value = -1;
return val;
}
}


public class A extends Thread {
private int max;
private DataShare dataShare;

public A (int n, DataShare ds) {
max = n;
dataShare = ds;
}

public void run() {
int i = 0;
while (i < max) {
if (dataShare.setValue(i)) {
i++;
}
}
}
}


public class B extends Thread {
private int total;
private DataShare dataShare;
private boolean running = false;

public B (DataShare ds) {
dataShare = ds;
total = 0;
}

public void run() {
running = true;
while (running) {
int nextValue = dataShare.getValue();
if (nextValue != -1) {
total += nextValue;
}
}
}

public int getTotal() {
return total;
}

public synchronized void endThread() {
running = false;
}
}

我知道这个简单的示例远非最佳,因为两个线程在等待设置/读取值时都浪费了宝贵的周期。我只是想让示例尽可能简单,同时仍然解决我想要表达的观点。

关于java:将类引用传递给另一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17940115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com