gpt4 book ai didi

Java如何向线程传递额外的对象

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

我认为这是不可能的,但我想告诉我的每个线程在特定对象上工作。像这样 -

class Tester implements Runnable{
String s1, s2;
Thread t1, t2;

test(){
t1 = new Thread(this, "t1");
t2 = new Thread(this, "t2");
t1.start();
t2.start();
}

public void run(){
if(this is t1){
s1="s1";
}
if(this is t2){
s2="s2";
}
}
}

我想以某种方式能够告诉 thread t1string s1 上运行代码和t2s2 。现在我只是通过检查Thread.currentThreat.getName()来做到这一点,但这不是一个好方法。另一种方法是匿名 Runnable有自己的字符串的类,并且只是 run对此,但是主线程如何获取这两个字符串呢?

最佳答案

为什么不传递不同的Thread的不同Runnable

Runnable r1 = new Runnable() { public void run() { /* this is r1 */ } };
Runnable r2 = new Runnable() { public void run() { /* this is r2 */ } };
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();

/编辑

创建一个可以实例化的类:

public class MyRunnable implements Runnable {
private final String s;

public MyRunnable(Stirng s) {
this.s = s;
}

public void run() {
// do something with s
}
}

Thread t1 = new Thread(new MyRunnable("s1"));
Thread t2 = new Thread(new MyRunnable("s2"));
t1.start();
t2.start();

/e2

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceExample {
private static class CallableExample implements Callable<Integer> {
private final Object foo;

private CallableExample(Object foo) {
this.foo = foo;
}

@Override
public Integer call() {
// do something and return it
return foo.hashCode();
}

}

public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService e = Executors.newFixedThreadPool(2);
Future<Integer> f1 = e.submit(new CallableExample("foo"));
Future<Integer> f2 = e.submit(new CallableExample("bar"));

System.out.println(f1.get());
System.out.println(f2.get());

e.shutdown();
}
}

Here这是关于 Executor 框架的一个很好的教程。

关于Java如何向线程传递额外的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17431371/

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