package cn.itcast_03;
/*
* 如何获取线程对象的名称呢?
* public final String getName():获取线程名称。
* 如何设置线程对象的名称呢?
* public final void setName(String name):设置线程的名称。
*
* 针对不是继承Thread类的子类该如何获取线程名称呢?
* public static Thread currentThread():返回当前正在执行的线程对象
* Thread.currentThread().getName();
*/
public class MyThreadDemo {
public static void main(String[] args) {
// 创建线程对象
// 无参构造+setXxx()
// MyThread my1 = new MyThread();
// MyThread my2 = new MyThread();
//
// // 调用方法设置名称
// my1.setName("朱茵");
// my2.setName("周星星");
// // 启动线程
// my1.start();
// my2.start();
// 带参构造方法给线程起名字
// MyThread my1 = new MyThread("朱茵");
// MyThread my2 = new MyThread("周星星");
//
// my1.start();
// my2.start();
// 我要获取main方法所在的线程对象的名称,该怎么办呢
System.out.println(Thread.currentThread().getName());
}
}
/*
名称为什么是:Thread-? 编号
class Thread{
private char name[];
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(String name) {
init(null, null, name, 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
// 大部分代码省略了
this.name = name.toCharArray();
}
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
public final String getName() {
return String.valueOf(name);
}
}
class MyThread extends Thread{
public MyThread(){
super();
}
}
*/
package cn.itcast_03;
public class MyThread extends Thread {
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int x = 0; x < 30; x++) {
System.out.println(getName() + ":" + x);
}
}
}
还没有评论,来说两句吧...