有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
当前回答
这个答案来得很晚,但也许有人会觉得它有用。它是关于如何在不声明命名类的情况下将参数传递给Runnable(对于内联程序来说很方便):
String someValue = "Just a demo, really...";
new Thread(new Runnable() {
private String myParam;
public Runnable init(String myParam) {
this.myParam = myParam;
return this;
}
@Override
public void run() {
System.out.println("This is called from another thread.");
System.out.println(this.myParam);
}
}.init(someValue)).start();
当然,您可以将start的执行推迟到某个更方便或合适的时刻。这取决于你init方法的签名(所以它可能需要更多和/或不同的参数),当然甚至它的名字,但基本上你得到了一个想法。
事实上,还有另一种将参数传递给匿名类的方法,即使用初始化块。考虑一下:
String someValue = "Another demo, no serious thing...";
int anotherValue = 42;
new Thread(new Runnable() {
private String myParam;
private int myOtherParam;
// instance initializer
{
this.myParam = someValue;
this.myOtherParam = anotherValue;
}
@Override
public void run() {
System.out.println("This comes from another thread.");
System.out.println(this.myParam + ", " + this.myOtherParam);
}
}).start();
所有都发生在初始化程序块内部。
其他回答
你需要在构造函数中将参数传递给Runnable对象:
public class MyRunnable implements Runnable {
public MyRunnable(Object parameter) {
// store parameter for later user
}
public void run() {
}
}
并这样调用它:
Runnable r = new MyRunnable(param_value);
new Thread(r).start();
您可以从Runnable派生一个类,并在构造过程中(例如)传入参数。
然后使用Thread启动它。开始(Runnable r);
如果你的意思是在线程运行时,那么只需在调用线程中保持对派生对象的引用,并调用适当的setter方法(在适当的地方同步)。
创建线程时,需要一个Runnable实例。传递形参最简单的方法是将它作为参数传递给构造函数:
public class MyRunnable implements Runnable {
private volatile String myParam;
public MyRunnable(String myParam){
this.myParam = myParam;
...
}
public void run(){
// do something with myParam here
...
}
}
MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();
如果你想在线程运行时改变参数,你可以简单地给你的runnable类添加一个setter方法:
public void setMyParam(String value){
this.myParam = value;
}
一旦你有了这个,你可以通过像这样调用来改变参数的值:
myRunnable.setMyParam("Goodbye World");
当然,如果您希望在参数更改时触发一个操作,则必须使用锁,这使事情变得相当复杂。
在Java 8中,你可以在并发API和ExecutorService中使用lambda表达式,作为直接使用线程的高级替代:
创建一个用于创建新线程的线程池 根据需要,但将重用之前构造的线程 可用。这些池通常会提高执行许多短期异步任务的程序的性能。
private static final ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> {
myFunction(myParam1, myParam2);
});
参见executors javadocs。
有一种将参数传递到可运行程序的简单方法。 代码:
public void Function(final type variable) {
Runnable runnable = new Runnable() {
public void run() {
//Code adding here...
}
};
new Thread(runnable).start();
}