Reputation: 2542
this is the code i have (sort of)
foo(a, b)
{
c = a.item;
bar(c);
b = a;
b.count--;
}
i want bar(c) to run in a separate thread.
So far this is what i have:
i make the class implement runnable.
I replace the bar(c) line with t = new Thread(this, "Demo Thread"); t.start();
and i create a function later in the code that looks like this:
public void run
{
bar(c);
}
the problem is that i dont know how to get c into run. can anyone explain how i can do this ?
Upvotes: 1
Views: 84
Reputation: 138884
I modified your code to run bar(c)
in its own thread.
foo(a, b)
{
final c = a.item;
new Thread() {
@Override
public void run() {
bar(c);
}
}.start();
b = a;
b.count--;
}
Essentially what you are doing is creating a new Thread
object that will just make the call to bar(c)
. You also need to make c
final in the method so you are allowed to pass it into the run
method of the anonymous inner class.
I would also like to note that using this method, the Thread
that runs bar
just goes off on its merry way and you have no way to monitor its progress. You may want to add some more robust logic to handle the flow of the program. (If it's needed.)
Upvotes: 3
Reputation: 32949
Create an instance of Runnable that takes a value in its constructor. Run the Runnable in the thread.
Upvotes: 1