简单介绍一下Thread类的方法
1、set/getName
设置和获取线程名字
Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i=0;i<10;i++){ System.out.println(i); } } }); t2.setName("我是线程2");
使用setName可以给一个线程设置一个名字
Thread t1 = new Thread(){ @Override public void run() { for (int i=0;i<10;i++){ System.out.println(this.getName()+i); } } };
使用getName()方法可以获得线程的名字
2、获取当前线程对象
Thread t1 = new Thread(){ @Override public void run() { for (int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+i); } } };
使用Thread类的静态方法currentThread可以获得那个当前的线程对象
3、线程休眠
Thread t1 = new Thread(){ @Override public void run() { for (int i=0;i<10;i++){ if (i==5) { try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName()+i); } } };
使用Thread类的静态方法sleep方法可以让当前线程休眠多少毫秒,线程在休眠期间,其他线程可以获得CPU资源
4、设置守护线程
t1.setDaemon(true);
设置一个线程为守护线程, 该线程不会单独执行, 当其他非守护线程都执行结束后, 自动退出。比如垃圾回收线程就是守护线程,要注意的是要将线程设置为守护线程,必须在线程调用start方法之前调用setDaemon方法
5、加入线程
public final void join() throws InterruptedException { join(0); }
当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续。
6、礼让线程
public static native void yield();
让线程放弃CPU资源,并不代表其他线程一定能抢到CPU资源,当前线程有可能继续执行。
7、停止线程
public void interrupt()
调用interupt方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程
要想停止线程,可以将interupt方法和interupted方法一起使用
看下面代码:
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(){ @Override public void run() { try { for (int i=0;i<100000;i++){ if (this.interrupted()){ System.out.println("我要结束了!!!"); throw new InterruptedException(); } System.out.println(getName()+i); } } catch (InterruptedException e) { e.printStackTrace(); } } }; try { t1.start(); Thread.sleep(500); t1.interrupt(); }catch (Exception e){ e.printStackTrace(); } }使用异常使线程停止。