Interthread Communication program
Class Producer implements Runnable
Q q;
Producer(Q q) {
this.q = q; // line- 5
new Thread(this, "Producer").start();
}
public void run(){
int i = 0;
while(true){
q.put(i++);
}
}
}
Hey can anyone please tell me : 1. At 开发者_如何学Pythonline 5, which q are these? 2. Why is, at line 6, no object is instantiated? Directly the start function is called? Thanks...
Line 5 - the q instance variable is set to whatever the value of q passed to Producers constructor is.
Line 6 - A new Thread is instantiated. It returns itself from the Constructor and the start method is immediately called.
this.q
is the instance variableq
declared in line 2- plain
q
is the constructor parameter declared in line 4 - In line 6, an object is instantiated via
new
, then thestart
method is immediately called on it. There just isn't any explicit reference to the object kept. However, since it was used to start a thread, it will be implicitly referred to in that thread and thus doesn't become eligible for garbage collection until the thread finishes.
At line 5, the class' private (this.)q is instantiated with the q passed in the constructor.
At line 6, a new Thread is created but the object is never used again, so it's just a short way of doing this.
Thread t = new Thread(this,"Producer");
t.start();
Is equivalent to
new Thread(this,"Producer").start();
- In the statement
this.q = q;
,this.q
refers to theq
field of the instance of the class, whileq
refers to the parameter. new Thread(this, "Producer")
creates a new instance of theThread
class so yes, an object is instantiated before calling thestart()
method.
At line 5, this.q
refers to the field q
of the Producer
object that is currently constructed. The second q
refers to the constructor argument, i.e. the Q
that has been passed to the construtor.
On line 6, there is a new Thread
object constructed. It's just not assigned to any variable. Instead the start()
method is directly called. This is a common pattern when no reference to the Thread
object is required.
You could replace it with this equivalent code:
Thread thread = new Thread(this, "Producer");
thread.start();
That would have the exact same effect.
精彩评论