线程的一些方法 取名啥的

public class ThreadDemo1 {
public static void main(String[] args) {
Thread mt1 = new MyThread("1号");
//mt1.setName("一号线程");
mt1.start();

Thread mt2 = new MyThread("2号");
//mt2.setName("一号线程");
mt2.start();

//哪个线程执行它, 他就得到哪个线程对象(当前线程对象)
//主线程的名称叫 main
Thread m = Thread.currentThread();
System.out.println(m.getName());
for (int i = 0; i<5; i++){
System.out.println(m.getName()+i);
}
}
}
class MyThread extends Thread{
public MyThread(String name) {
//为当前线程对象设置名称, 送给父类的有参构造器初始化名称
super(name);
}
@Override
public void run() {
for (int i = 0; i<5; i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}

---------
public class ThreadDemo02 {
public static void main(String[] args) throws Exception{
for (int i = 1; i <= 5; i++) {
System.out.println("输出"+ i);
if (i == 3){
//让线程进入休眠状态
Thread.sleep(3000);
}
}
}
}

posted on 2022-03-30 15:55  我要当程序源  阅读(26)  评论(0编辑  收藏  举报

导航