问题描述
我正在学习Java中的多线程。
在这里,我陷入了getId()
方法的困境。
如何返回“ 8”?
然后,我也对t1的“ Thread-0”和t2的“ Thread-1”有疑问,这些是getName()
方法的初始值吗?
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
输出值
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
1楼
我被getId()方法困住了
作为getId状态的Javadoc
/**
* Returns the identifier of this Thread. The thread ID is a positive
* <tt>long</tt> number generated when this thread was created.
* The thread ID is unique and remains unchanged during its lifetime.
* When a thread is terminated, this thread ID may be reused.
*
* @return this thread's ID.
* @since 1.5
*/
public long getId() {
return tid;
}
和
tid = nextThreadID();
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
JVM具有内部线程,因此您创建的第一个线程可能是第9个线程。
注意: main
是一个线程。
然后我也对t1的“ Thread-0”和t2的“ Thread-1”感到怀疑,这是getName()方法的初始值吗?
同样,创建线程时会生成默认名称
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
* {@code (null, target, gname)}, where {@code gname} is a newly generated
* name. Automatically generated names are of the form
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
*
* @param target
* the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this classes {@code run} method does
* nothing.
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
2楼
它是在方法中生成的,该方法只是计数。
源代码中的一些摘要。
public long getId() {
return tid;
}
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
// lots of other stuff
tid = nextThreadID();
}
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
其他构造函数对init
进行类似的调用