setname方法每个线程取名
需要创建构造器 线程设置名字
package Thread_api_test;// 继承Thread类
public class MyThread extends Thread {//创建构造器 线程设置名字public MyThread(String name){super(name);}@Overridepublic void run() {super.run();Thread m=Thread.currentThread();for (int i = 1; i <= 3; i++) {System.out.println(m.getName()+"子类线程输出:" + i);}}
}
package Thread_api_test;public class THreadTest {public static void main(String[] args) {Thread T1 = new MyThread("1号线程");// T1.setName("子线程0");// Thread-1T1.start();System.out.println(T1.getName());Thread T2 = new MyThread("1号线程"); //Thread-0// T2.setName("子线程1");T2.start();System.out.println(T2.getName());//主线程对象的名字//那个线程执行它 他就会得到那个线程对象Thread m=Thread.currentThread();// m.setName("最牛的线程");System.out.println(m.getName());for (int i = 1; i <=5; i++) {System.out.println(m.getName()+"线程输出:" + i);}}
}
join的小案例
package Thread_api_test;public class THreadTest1 {public static void main(String[] args) throws Exception{for (int i = 1; i <5 ; i++) {if (i==3){System.out.println(i);//循环停5秒以后再执行Thread.sleep(5000);}}//三个线程指定的循序执行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();}
}