英文:
How to use Java Exchanger?
问题
import java.util.Random;
import java.util.concurrent.Exchanger;
class CustomThread extends Thread {
private Exchanger<Integer> exchange = new Exchanger<>();
CustomThread() {
}
private void testExchanger() throws InterruptedException {
Random r = new Random();
int sendx = r.nextInt(1000);
int recievex = exchange.exchange(sendx);
System.out.println(currentThread().getId() + " received " + recievex);
}
public void run() {
try {
testExchanger();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Thread[] threads = new Thread[6];
for (int i = 0; i < threads.length; i++) {
threads[i] = new CustomThread();
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
英文:
I am trying to test out the functions of an exchanger, where I can create some data in a thread, and then transfer it to another thread concurrently. I was hoping the exchanger would do this. The exchange method used in a thread is supposed to go into a waiting state where it waits for another thread to be at this state, and then exchanges information. However, all of my threads just keep waiting forever and never interact. How is this possible? If they are waiting for each other then shouldn't they continue with the action and go to the next line? Thanks for any advice on this.
import java.util.Random;
import java.util.concurrent.Exchanger;
class CustomThread extends Thread {
private Exchanger<Integer> exchange = new Exchanger<>();
CustomThread() {
}
private void testExchanger() throws InterruptedException {
Random r = new Random();
int sendx = r.nextInt(1000);
int recievex = exchange.exchange(sendx);
System.out.println(currentThread().getId() + " recieved " + recievex);
}
public void run() {
try {
testExchanger();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Thread[] threads = new Thread[6];
for (int i = 0; i < threads.length; i++) {
threads[i] = new CustomThread();
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
</details>
# 答案1
**得分**: 1
更改这一行:
```java
private Exchanger<Integer> exchange = new Exchanger<>();
为这样的:
private static Exchanger<Integer> exchange = new Exchanger<>();
解释:
每个线程都会创建一个独立的交换器(Exchanger)实例。将其声明为静态(static)会使得一个 Exchanger
实例在各个线程之间共享。
英文:
Change this line
private Exchanger<Integer> exchange = new Exchanger<>();
to this
private static Exchanger<Integer> exchange = new Exchanger<>();
Explanation:
Each of your thread creates a separate exchanger. Making it static will cause that the instance of an Exchanger
will be shared between the threads.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论