package com.itheima.d2;
public class ThreadTest1 {
public static void main(String[] args) {
Thread t1 = new MyThread("子线程1");
//t1.setName("子线程1");
t1.start();
System.out.println(t1.getName());//获得子线程名字
Thread t2 = new MyThread("子线程2");
//t2.setName("子线程2");
t2.start();
System.out.println(t2.getName());//获得子线程名字
//主线程对象的名字
//哪个线程执行它,它就会得到哪个线程的名字
Thread m = Thread.currentThread();
m.setName("主线程");
System.out.println(m.getName());//获得主线程的名字main
for (int i = 1; i <= 5; i++) {
System.out.println(m.getName() + "输出" + i);
}
}
}
子线程
package com.itheima.d2;
public class MyThread extends Thread{
public MyThread(String name){
super(name);//为当前线程设置名字
}
@Override
public void run() {
//哪个线程执行它,它就会得到哪个线程的名字
Thread t = Thread.currentThread();
for (int i = 1; i <= 5; i++) {
System.out.println(t.getName() + "输出" + i);
}
}
}
join与sleep的用法
package com.itheima.d2;
public class ThreadTest2 {
public static void main(String[] args) throws Exception {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
//休眠5秒
if (i == 3){
//让当前执行的程序暂停5秒,再继续执行
Thread.sleep(5000);
}
}
//join方法的使用,让当前调用在个方法的线程先执行完
Thread t1 = new MyThread("子线程1");
t1.start();
t1.join();
Thread t2 = new MyThread("子线程2");
t2.start();
t2.join();
Thread t3 = new MyThread("子线程3");
t3.start();
t3.join();
}
}