5. Thread类中常用的一些方法
5.1 线程休眠方法
public class MyThread extends Thread{ @Override public void run() { for (int i = 0; i <20 ; i++) { try { //秒杀--- Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~~~~"+i); } } }
5.2 放弃 yieId方法
yield 当前线程让出cpu-参与下次的竞争
public class MyThread extends Thread{ @Override public void run() { for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~~~~"+i); Thread.yield();//当前线程让出cpu参与下次的竞争。 System.out.println("~~~~~~~~~~~~~~~~"); } } }
5.3 join加入当前线程上
插入的线程执行完毕后,当前线程才会执行。
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread t1=new MyThread();
t1.setName("线程A");
MyThread2 t2=new MyThread2();
t2.setName("线程B");
t1.start();
t2.start();
t1.join(); //t1加入主线程上,主线程需要等t1执行完毕后才会执行. 如果主线程需要等带t1和t2线程的执行结果 做下一步操作时。
for (int i = 0; i <20 ; i++) {
Thread.sleep(10);
System.out.println("main~~~~~~~~~~~~~~~~~~~~~"+i);
}
}
}
5.4 setDaemon()
设置线程为守护线程,当所有线程执行完毕后,守护线程也会终止。
//JDK--默认就有一个守护线程.GC垃圾回收。
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread t1=new MyThread();
t1.setName("线程A");
t1.setDaemon(true);//设置t1为守护线程
t1.start();
for (int i = 0; i <20 ; i++) {
System.out.println("main~~~~~~~~~~~~~~~~~~~~~"+i);
}
}
}