上文介紹了Tread的實例方法,本文再介紹下Thread的靜態方法。ide
currentThread方法返回當前線程的Objectthis
public class Thread1 extends Thread{ static{ System.out.println(Thread.currentThread().getName()+" --> static"); } public Thread1() { System.out.println(Thread.currentThread().getName()+" --> 構造方法"); } @Override public void run() { System.out.println(Thread.currentThread().getName()+" --> run"); } }
public static void main(String[] args) { Thread1 t1 = new Thread1(); t1.start(); }
執行結果:.net
main --> static main --> 構造方法 Thread-0 --> run
Thread1在初始化的過程當中都是在主線程執行,start後開啓新線程執行。線程
sleep方法是事當前線程睡眠(暫停)n毫秒。在睡眠過程當中,線程會讓出cpu,但不會失去已鎖定的資源。code
Thread t = new Thread(new Runnable() { @Override public void run() { try { Long t1 = System.currentTimeMillis(); System.out.println("start at:"+t1); Thread.sleep(2000); Long t2 = System.currentTimeMillis(); System.out.println("end at:"+t2); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start();
執行結果:blog
start at:1511096714406 end at:1511096716407
考慮到系統時間分配等因素,執行結果都會大於等於指定的毫秒數,但不會差太多。另外sleep方法會拋出InterruptedException 的異常,在上文中也有講到。資源
yield方法是讓出cpu的使用,讓出多少時間是不肯定的。get
public class YieldTest extends Thread{ public YieldTest(String name) { super(name); } @Override public void run() { for (int i = 1; i <= 50; i++) { System.out.println("" + this.getName() + "-----" + i); if (i == 30) { this.yield(); } } } public static void main(String[] args) { YieldTest yt1 = new YieldTest("張三"); YieldTest yt2 = new YieldTest("李四"); yt1.start(); yt2.start(); } }
部分的執行結果:io
...... 張三-----28 張三-----29 張三-----30 李四-----17 李四-----18 李四-----19 李四-----20 .....
固然每次執行的結果可能都不同,這裏能夠看在執行到i==30時,'張三'讓出了cpu使用,'李四'則開始執行。class
返回當前線程是否被中斷,實現就是
return currentThread().isInterrupted(true);
holdsLock是判斷某個資源是否被線程鎖定,
public class Thread1 extends Thread{ private Object obj = new Object(); @Override public void run() { synchronized (obj) { System.out.println("holdsLock1="+Thread.holdsLock(obj)); } System.out.println("holdsLock2="+Thread.holdsLock(obj)); } }
public static void main(String[] args) { Thread1 t1 = new Thread1(); t1.start();
執行結果:
holdsLock1=true holdsLock2=false