Originally posted by Dave Reinhardt:
questions about this code:
1. If you passed a single a1 thread to the two threads t and t1, would it then print 1-10 twice one after the other? That's what I would assume since now there are two threads working on a single runnable. see below
A a1=new A();
Thread t=new Thread(a1);
Thread t1=new Thread(a1);
t.start();
t1.start();
2. I know that Thread implements Runnable, and so that is probably why you can pass another thread to a thread constructor, but why would this method be preferable over creating a Runnable instance and passing it instead? It seems overly confusing to pass threads to threads, so I'm wondering if this design is real-world or just contrived for an exam question? In the first example are there still only two threads (ignoring main)since start is never called on a1 and a2?
2. It's contrived alright. The thread objects a1 and a2 are only good for their Runnableness. There are two threads and they are referenced by t and t1.
1. If you use just one of the objects to synchronize on, notice that the instance variable count is shared and it's that that is being incremented and printed. So you will get 1 to 20 printed not two times 1 to 10.