Can anyone suggest to me how I can pass a parameter to a thread?
谁能告诉我如何将参数传递给线程吗?
Also, how does it work for anonymous classes?
另外,它对于匿名类如何工作?
16 个解决方案
#1
298
You need to pass the parameter in the constructor to the Runnable object:
您需要将构造函数中的参数传递给Runnable对象:
public class MyRunnable implements Runnable {
public MyRunnable(Object parameter) {
// store parameter for later user
}
public void run() {
}
}
and invoke it thus:
并调用它:
Runnable r = new MyRunnable(param_value);
new Thread(r).start();
#2
97
For Anonymous classes:
In response to question edits here is how it works for Anonymous classes
作为对问题编辑的回应,本文介绍了它如何用于匿名类
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
Named classes:
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
您有一个扩展线程(或实现Runnable)的类,以及一个您想要传递的参数的构造函数。然后,当您创建新线程时,您必须传入参数,然后启动线程,如下所示:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
Runnable是比线程BTW更好的解决方案。所以我更喜欢:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
这个答案基本上与这个类似的问题相同:如何将参数传递给线程对象
#3
34
via constructor of a Runnable or Thread class
通过可运行或线程类的构造函数
class MyThread extends Thread {
private String to;
public MyThread(String to) {
this.to = to;
}
@Override
public void run() {
System.out.println("hello " + to);
}
}
public static void main(String[] args) {
new MyThread("world!").start();
}
#4
15
When you create a thread, you need an instance of Runnable
. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:
创建线程时,需要一个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();
If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:
如果您想要在线程运行时更改参数,您可以向您的runnable类添加一个setter方法:
public void setMyParam(String value){
this.myParam = value;
}
Once you have this, you can change the value of the parameter by calling like this:
一旦有了这个参数,就可以通过如下调用来更改参数的值:
myRunnable.setMyParam("Goodbye World");
Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.
当然,如果您想要在参数更改时触发操作,您将必须使用锁,这会使事情变得非常复杂。
#5
10
This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable
without even declaring named class (handy for inliners):
这个答案来得很晚,但也许有人会觉得它有用。它是关于如何将参数传递给Runnable,甚至不声明命名类(对于inliner来说很方便):
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();
Of course you can postpone execution of start
to some more convenient or appropriate moment. And it is up to you what will be the signature of init
method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.
当然,您可以将start的执行推迟到更方便或更合适的时刻。init方法的签名是由你决定的(所以它可能会有更多和/或不同的参数)当然还有它的名字,但是基本上你会有一个想法。
In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:
事实上,还有另一种方法可以使用初始化器块将参数传递给匿名类。考虑一下:
String someValue = "Another demo, no serious thing...";
int anotherValue = 42;
new Thread(new Runnable() {
private String myParam;
private int myOtherParam;
{
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();
So all happens inside of the initializer block.
所有这些都发生在初始化块内部。
#6
8
To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.
要创建一个线程,通常需要创建自己的Runnable实现。将参数传递给该类构造函数中的线程。
class MyThread implements Runnable{
private int a;
private String b;
private double c;
public MyThread(int a, String b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public void run(){
doSomething(a, b, c);
}
}
#7
7
You can either extend the Thread
class
or the Runnable
class
and provide parameters as you want. There are simple examples in the docs. I'll port them here:
您可以扩展Thread类或Runnable类,并根据需要提供参数。文档中有一些简单的例子。在这里我会端口:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeThread p = new PrimeThread(143);
p.start();
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
#8
6
Either write a class that implements Runnable, and pass whatever you need in a suitably defined constructor, or write a class that extends Thread with a suitably defined constructor that calls super() with appropriate parameters.
要么编写实现Runnable的类,并在适当定义的构造函数中传递所需的任何内容,要么编写一个类,该类使用适当定义的构造函数扩展线程,该构造函数使用适当的参数调用super()。
#9
2
You can derive a class from Runnable, and during the construction (say) pass the parameter in.
您可以从Runnable派生类,在构建过程中(比方说)传递参数。
Then launch it using Thread.start(Runnable r);
然后使用线程启动它。开始(Runnable r);
If you mean whilst the thread is running, then simply hold a reference to your derived object in the calling thread, and call the appropriate setter methods (synchronising where appropriate)
如果您是指在线程运行时,那么只需在调用线程中保存对派生对象的引用,并调用适当的setter方法(在适当的情况下进行同步)
#10
2
Parameter passing via the start() and run() methods:
通过start()和run()方法传递的参数:
// Tester
public static void main(String... args) throws Exception {
ThreadType2 t = new ThreadType2(new RunnableType2(){
public void run(Object object) {
System.out.println("Parameter="+object);
}});
t.start("the parameter");
}
// New class 1 of 2
public class ThreadType2 {
final private Thread thread;
private Object objectIn = null;
ThreadType2(final RunnableType2 runnableType2) {
thread = new Thread(new Runnable() {
public void run() {
runnableType2.run(objectIn);
}});
}
public void start(final Object object) {
this.objectIn = object;
thread.start();
}
// If you want to do things like setDaemon(true);
public Thread getThread() {
return thread;
}
}
// New class 2 of 2
public interface RunnableType2 {
public void run(Object object);
}
#11
1
There is a simple way of passing parameters into runnables. Code:
有一种简单的方法可以将参数传递给runnables。代码:
public void Function(final type variable) {
Runnable runnable = new Runnable() {
public void run() {
//Code adding here...
}
};
new Thread(runnable).start();
}
#12
1
As of Java 8, you can use a lambda to capture parameters that are effectively final. For example:
从Java 8开始,您可以使用lambda来捕获有效的最终参数。例如:
final String param1 = "First param";
final int param2 = 2;
new Thread(() -> {
// Do whatever you want here: param1 and param2 are in-scope!
System.out.println(param1);
System.out.println(param2);
}).start();
#13
1
In Java 8 you can use lambda
expressions with the Concurrency API & the ExecutorService
as a higher level replacement for working with threads directly:
在Java 8中,您可以使用lambda表达式与并发API & ExecutorService作为更高级别的替换,直接使用线程:
newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks.newCachedThreadPool()创建了一个线程池,该线程池根据需要创建新的线程,但是当以前构造的线程可用时,会重用它们。这些池通常会提高执行许多短期异步任务的程序的性能。
private static final ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> {
myFunction(myParam1, myParam2);
});
See also executors
javadocs.
也看到执行人javadocs。
#14
0
One further option; this approach lets you use the Runnable item like an asynchronous function call. If your task does not need to return a result, e.g. it just performs some action you don't need to worry about how you pass back an "outcome".
另外一个选择;这种方法允许您使用可运行项,如异步函数调用。如果你的任务不需要返回结果,例如,它只执行一些操作,你不需要担心你如何传递一个“结果”。
This pattern lets you reuse an item, where you need some kind of internal state. When not passing parameter(s) in the constructor care is needed to mediate the programs access to parameters. You may need more checks if your use-case involves different callers, etc.
此模式允许重用项,其中需要某种内部状态。当不在构造函数中传递参数时,需要关心如何协调程序对参数的访问。如果您的用例涉及不同的调用者等,您可能需要更多的检查。
public class MyRunnable implements Runnable
{
private final Boolean PARAMETER_LOCK = false;
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void setParameter( final X newParameter ){
boolean done = false;
synchronize( PARAMETER_LOCK )
{
if( null == parameter )
{
parameter = newParameter;
done = true;
}
}
if( ! done )
{
throw new RuntimeException("MyRunnable - Parameter not cleared." );
}
}
public void clearParameter(){
synchronize( PARAMETER_LOCK )
{
parameter = null;
}
}
public void run() {
X localParameter;
synchronize( PARAMETER_LOCK )
{
localParameter = parameter;
}
if( null != localParameter )
{
clearParameter(); //-- could clear now, or later, or not at all ...
doSomeStuff( localParameter );
}
}
}
}
Thread t = new Thread(new MyRunnable(parameter)); t.start();
线程t =新线程(新MyRunnable(参数));t.start();
If you need a result of processing, you will also need to coordinate completion of MyRunnable when the sub-task finishes. You could pass a call back or just wait on the Thread 't', etc.
如果需要处理的结果,还需要在子任务完成时协调MyRunnable的完成。您可以回传一个调用,或者只是在线程t上等待,等等。
#15
0
Specially for Android
For callback purposes I usually implement my own generic Runnable
with input parameter(s):
为了回调目的,我通常使用输入参数实现我自己的通用Runnable:
public interface Runnable<TResult> {
void run(TResult result);
}
Usage is simple:
使用很简单:
myManager.doCallbackOperation(new Runnable<MyResult>() {
@Override
public void run(MyResult result) {
// do something with the result
}
});
In manager:
在经理:
public void doCallbackOperation(Runnable<MyResult> runnable) {
new AsyncTask<Void, Void, MyResult>() {
@Override
protected MyResult doInBackground(Void... params) {
// do background operation
return new MyResult(); // return resulting object
}
@Override
protected void onPostExecute(MyResult result) {
// execute runnable passing the result when operation has finished
runnable.run(result);
}
}.execute();
}
#16
0
No you can't pass parameters to the run()
method. The signature tells you that (it has no parameters). Probably the easiest way to do this would be to use a purpose-built object that takes a parameter in the constructor and stores it in a final variable:
不,您不能将参数传递给run()方法。签名告诉您(它没有参数)。可能最简单的方法是使用一个特别构建的对象,它在构造函数中接受一个参数并将其存储在一个最终变量中:
public class WorkingTask implements Runnable
{
private final Object toWorkWith;
public WorkingTask(Object workOnMe)
{
toWorkWith = workOnMe;
}
public void run()
{
//do work
}
}
//...
Thread t = new Thread(new WorkingTask(theData));
t.start();
Once you do that - you have to be careful of the data integrity of the object you pass into the 'WorkingTask'. The data will now exist in two different threads so you have to make sure it is Thread Safe.
一旦您这样做了——您必须注意传递到“WorkingTask”中的对象的数据完整性。数据现在存在于两个不同的线程中,所以您必须确保线程安全。
#1
298
You need to pass the parameter in the constructor to the Runnable object:
您需要将构造函数中的参数传递给Runnable对象:
public class MyRunnable implements Runnable {
public MyRunnable(Object parameter) {
// store parameter for later user
}
public void run() {
}
}
and invoke it thus:
并调用它:
Runnable r = new MyRunnable(param_value);
new Thread(r).start();
#2
97
For Anonymous classes:
In response to question edits here is how it works for Anonymous classes
作为对问题编辑的回应,本文介绍了它如何用于匿名类
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
Named classes:
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
您有一个扩展线程(或实现Runnable)的类,以及一个您想要传递的参数的构造函数。然后,当您创建新线程时,您必须传入参数,然后启动线程,如下所示:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
Runnable是比线程BTW更好的解决方案。所以我更喜欢:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
这个答案基本上与这个类似的问题相同:如何将参数传递给线程对象
#3
34
via constructor of a Runnable or Thread class
通过可运行或线程类的构造函数
class MyThread extends Thread {
private String to;
public MyThread(String to) {
this.to = to;
}
@Override
public void run() {
System.out.println("hello " + to);
}
}
public static void main(String[] args) {
new MyThread("world!").start();
}
#4
15
When you create a thread, you need an instance of Runnable
. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:
创建线程时,需要一个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();
If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:
如果您想要在线程运行时更改参数,您可以向您的runnable类添加一个setter方法:
public void setMyParam(String value){
this.myParam = value;
}
Once you have this, you can change the value of the parameter by calling like this:
一旦有了这个参数,就可以通过如下调用来更改参数的值:
myRunnable.setMyParam("Goodbye World");
Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.
当然,如果您想要在参数更改时触发操作,您将必须使用锁,这会使事情变得非常复杂。
#5
10
This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable
without even declaring named class (handy for inliners):
这个答案来得很晚,但也许有人会觉得它有用。它是关于如何将参数传递给Runnable,甚至不声明命名类(对于inliner来说很方便):
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();
Of course you can postpone execution of start
to some more convenient or appropriate moment. And it is up to you what will be the signature of init
method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.
当然,您可以将start的执行推迟到更方便或更合适的时刻。init方法的签名是由你决定的(所以它可能会有更多和/或不同的参数)当然还有它的名字,但是基本上你会有一个想法。
In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:
事实上,还有另一种方法可以使用初始化器块将参数传递给匿名类。考虑一下:
String someValue = "Another demo, no serious thing...";
int anotherValue = 42;
new Thread(new Runnable() {
private String myParam;
private int myOtherParam;
{
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();
So all happens inside of the initializer block.
所有这些都发生在初始化块内部。
#6
8
To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.
要创建一个线程,通常需要创建自己的Runnable实现。将参数传递给该类构造函数中的线程。
class MyThread implements Runnable{
private int a;
private String b;
private double c;
public MyThread(int a, String b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public void run(){
doSomething(a, b, c);
}
}
#7
7
You can either extend the Thread
class
or the Runnable
class
and provide parameters as you want. There are simple examples in the docs. I'll port them here:
您可以扩展Thread类或Runnable类,并根据需要提供参数。文档中有一些简单的例子。在这里我会端口:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeThread p = new PrimeThread(143);
p.start();
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
#8
6
Either write a class that implements Runnable, and pass whatever you need in a suitably defined constructor, or write a class that extends Thread with a suitably defined constructor that calls super() with appropriate parameters.
要么编写实现Runnable的类,并在适当定义的构造函数中传递所需的任何内容,要么编写一个类,该类使用适当定义的构造函数扩展线程,该构造函数使用适当的参数调用super()。
#9
2
You can derive a class from Runnable, and during the construction (say) pass the parameter in.
您可以从Runnable派生类,在构建过程中(比方说)传递参数。
Then launch it using Thread.start(Runnable r);
然后使用线程启动它。开始(Runnable r);
If you mean whilst the thread is running, then simply hold a reference to your derived object in the calling thread, and call the appropriate setter methods (synchronising where appropriate)
如果您是指在线程运行时,那么只需在调用线程中保存对派生对象的引用,并调用适当的setter方法(在适当的情况下进行同步)
#10
2
Parameter passing via the start() and run() methods:
通过start()和run()方法传递的参数:
// Tester
public static void main(String... args) throws Exception {
ThreadType2 t = new ThreadType2(new RunnableType2(){
public void run(Object object) {
System.out.println("Parameter="+object);
}});
t.start("the parameter");
}
// New class 1 of 2
public class ThreadType2 {
final private Thread thread;
private Object objectIn = null;
ThreadType2(final RunnableType2 runnableType2) {
thread = new Thread(new Runnable() {
public void run() {
runnableType2.run(objectIn);
}});
}
public void start(final Object object) {
this.objectIn = object;
thread.start();
}
// If you want to do things like setDaemon(true);
public Thread getThread() {
return thread;
}
}
// New class 2 of 2
public interface RunnableType2 {
public void run(Object object);
}
#11
1
There is a simple way of passing parameters into runnables. Code:
有一种简单的方法可以将参数传递给runnables。代码:
public void Function(final type variable) {
Runnable runnable = new Runnable() {
public void run() {
//Code adding here...
}
};
new Thread(runnable).start();
}
#12
1
As of Java 8, you can use a lambda to capture parameters that are effectively final. For example:
从Java 8开始,您可以使用lambda来捕获有效的最终参数。例如:
final String param1 = "First param";
final int param2 = 2;
new Thread(() -> {
// Do whatever you want here: param1 and param2 are in-scope!
System.out.println(param1);
System.out.println(param2);
}).start();
#13
1
In Java 8 you can use lambda
expressions with the Concurrency API & the ExecutorService
as a higher level replacement for working with threads directly:
在Java 8中,您可以使用lambda表达式与并发API & ExecutorService作为更高级别的替换,直接使用线程:
newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks.newCachedThreadPool()创建了一个线程池,该线程池根据需要创建新的线程,但是当以前构造的线程可用时,会重用它们。这些池通常会提高执行许多短期异步任务的程序的性能。
private static final ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> {
myFunction(myParam1, myParam2);
});
See also executors
javadocs.
也看到执行人javadocs。
#14
0
One further option; this approach lets you use the Runnable item like an asynchronous function call. If your task does not need to return a result, e.g. it just performs some action you don't need to worry about how you pass back an "outcome".
另外一个选择;这种方法允许您使用可运行项,如异步函数调用。如果你的任务不需要返回结果,例如,它只执行一些操作,你不需要担心你如何传递一个“结果”。
This pattern lets you reuse an item, where you need some kind of internal state. When not passing parameter(s) in the constructor care is needed to mediate the programs access to parameters. You may need more checks if your use-case involves different callers, etc.
此模式允许重用项,其中需要某种内部状态。当不在构造函数中传递参数时,需要关心如何协调程序对参数的访问。如果您的用例涉及不同的调用者等,您可能需要更多的检查。
public class MyRunnable implements Runnable
{
private final Boolean PARAMETER_LOCK = false;
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void setParameter( final X newParameter ){
boolean done = false;
synchronize( PARAMETER_LOCK )
{
if( null == parameter )
{
parameter = newParameter;
done = true;
}
}
if( ! done )
{
throw new RuntimeException("MyRunnable - Parameter not cleared." );
}
}
public void clearParameter(){
synchronize( PARAMETER_LOCK )
{
parameter = null;
}
}
public void run() {
X localParameter;
synchronize( PARAMETER_LOCK )
{
localParameter = parameter;
}
if( null != localParameter )
{
clearParameter(); //-- could clear now, or later, or not at all ...
doSomeStuff( localParameter );
}
}
}
}
Thread t = new Thread(new MyRunnable(parameter)); t.start();
线程t =新线程(新MyRunnable(参数));t.start();
If you need a result of processing, you will also need to coordinate completion of MyRunnable when the sub-task finishes. You could pass a call back or just wait on the Thread 't', etc.
如果需要处理的结果,还需要在子任务完成时协调MyRunnable的完成。您可以回传一个调用,或者只是在线程t上等待,等等。
#15
0
Specially for Android
For callback purposes I usually implement my own generic Runnable
with input parameter(s):
为了回调目的,我通常使用输入参数实现我自己的通用Runnable:
public interface Runnable<TResult> {
void run(TResult result);
}
Usage is simple:
使用很简单:
myManager.doCallbackOperation(new Runnable<MyResult>() {
@Override
public void run(MyResult result) {
// do something with the result
}
});
In manager:
在经理:
public void doCallbackOperation(Runnable<MyResult> runnable) {
new AsyncTask<Void, Void, MyResult>() {
@Override
protected MyResult doInBackground(Void... params) {
// do background operation
return new MyResult(); // return resulting object
}
@Override
protected void onPostExecute(MyResult result) {
// execute runnable passing the result when operation has finished
runnable.run(result);
}
}.execute();
}
#16
0
No you can't pass parameters to the run()
method. The signature tells you that (it has no parameters). Probably the easiest way to do this would be to use a purpose-built object that takes a parameter in the constructor and stores it in a final variable:
不,您不能将参数传递给run()方法。签名告诉您(它没有参数)。可能最简单的方法是使用一个特别构建的对象,它在构造函数中接受一个参数并将其存储在一个最终变量中:
public class WorkingTask implements Runnable
{
private final Object toWorkWith;
public WorkingTask(Object workOnMe)
{
toWorkWith = workOnMe;
}
public void run()
{
//do work
}
}
//...
Thread t = new Thread(new WorkingTask(theData));
t.start();
Once you do that - you have to be careful of the data integrity of the object you pass into the 'WorkingTask'. The data will now exist in two different threads so you have to make sure it is Thread Safe.
一旦您这样做了——您必须注意传递到“WorkingTask”中的对象的数据完整性。数据现在存在于两个不同的线程中,所以您必须确保线程安全。