一个线程的创建肯定是由另一个线程创建。
被创建线程的父线程就是创建他的线程。
private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) { if (name == null) { throw new NullPointerException("name cannot be null"); } this.name = name; Thread parent = currentThread();//父线程 SecurityManager security = System.getSecurityManager(); //…… }
一、线程命名和取得
线程的所有操作方法几乎都在Thread类中定义好了
从本质上上来讲,多线程的运行状态并不是固定的,唯一的区别就在于线程的名称上。
起名:尽可能避免重名,或者避免修改名称。
在thread类中提供如下方法:
构造方法:public Thread(Runnable target, String name)
设置名字:public final synchronized void setName(String name)
取得名字:public final String getName()
既然线程本身是不缺定的状态,所以如果要取得线程名字的话,那么唯一能做的就是取得当前线程的名字。
所以在Thread类中有提供如下方法:
public static native Thread currentThread();
示例1:
class MyThread6 implements Runnable { @Override public void run() {// 主方法 for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ",i:" + i); } } }