Briefly introduce the methods of the Thread class
1、set/getName
Set and get thread name
Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i=0;i<10;i++){ System.out.println(i); } } }) ; t2.setName( " I am thread 2" ) ;
Use setName to set a name for a thread
Thread t1 = new Thread(){ @Override public void run() { for (int i=0;i<10;i++){ System.out.println(this.getName()+i); } } };
Use the getName() method to get the name of the thread
2. Get the current thread object
Thread t1 = new Thread(){ @Override public void run() { for (int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+i); } } };
Use the static method currentThread of the Thread class to get the current thread object
3. Thread sleep
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); } } };
Using the static method sleep method of the Thread class, how many milliseconds can the current thread sleep? During the sleep period, other threads can obtain CPU resources.
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 () ; } }Use an exception to stop the thread.