Java how to pass a thread an extra object

I dont think this is possible, but I want to tell each of my threads to work on a specific object. Sorta like this -

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";
        }
    }
}

I want to somehow be able to tell thread t1 to run code on string s1 and t2 on s2. Right now I simply do it by checkiing Thread.currentThreat.getName(), but thats not a good way. The alternative would be to make an anonymous Runnable class that has its own string and just run on that, but then how does the main thread get both of the strings after?

Upvotes: 0

Views: 113

Answers (2)

i would suggest use of Thread Local

you can visit the dummy examples from here and here

Upvotes: 0

Jeffrey
Jeffrey

Reputation: 44808

Why not pass the different Threads different Runnables?

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();

/edit

Create a class you can instantiate:

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's a good tutorial on the Executor framework.

Upvotes: 8

Related Questions