use*_*996 0 java multithreading
我正在网上学习Java的线程,我是初学者,我在理解一些概念方面遇到了困难.谁能帮我?
链接我正在学习:http://www.codeproject.com/Articles/616109/Java-Thread-Tutorial
问题:
public class Core {
public static void main(String[] args) {
Runnable r0,r1;//pointers to a thread method
r0=new FirstIteration("Danial"); //init Runnable, and pass arg to thread 1
SecondIteration si=new SecondIteration();
si.setArg("Pedram");// pass arg to thread 2
r1=si; //<~~~ What is Happening here??
Thread t0,t1;
t0=new Thread(r0);
t1=new Thread(r1);
t0.start();
t1.start();
System.out.print("Threads started with args, nothing more!\n");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:FirstIteration和SceondIteration的代码
class FirstIteration implements Runnable{
public FirstIteration(String arg){
//input arg for this class, but in fact input arg for this thread.
this.arg=arg;
}
private String arg;
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.print("Hello from 1st. thread, my name is "+
arg+"\n");//using the passed(arg) value
}
}
}
class SecondIteration implements Runnable{
public void setArg(String arg){//pass arg either by constructors or methods.
this.arg=arg;
}
String arg;
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.print("2)my arg is="+arg+", "+i+"\n");
}
}
}
Run Code Online (Sandbox Code Playgroud)
R1 = SI; <~~~这里发生了什么?*
参考作业.
您正在创建的参考副本si在r1.因此,该声明后,双方r1并si会指向同一个对象.
______________________
si ------> |new SecondIteration();| // You have 1 reference to this object
------------------------
r1 = si; // Make Runnable reference `r1` point the same object that `si` refers
______________________
si ------> |new SecondIteration();| // Now you have 2 reference to this object
------------------------
^
|
r1 ----------
Run Code Online (Sandbox Code Playgroud)
实际上,他们可以简单地完成:
r1 = new SecondIteration();
Run Code Online (Sandbox Code Playgroud)
而不是那两个步骤.但是,因为setArg()方法未在Runnable接口中声明.所以,要调用它,你必须进行类型转换,如下所示:
((SecondIteration)r1).setArg();
Run Code Online (Sandbox Code Playgroud)
这可能不太可读,这就是为什么他们可能将其分为两个步骤:
SecondIteration si = new SecondIteration();
si.setArg("Pedram");
r1=si;
Run Code Online (Sandbox Code Playgroud)