Java多線程入門中幾個常用的方法
阿新 • • 發佈:2018-10-13
-s lse row src mat mil 單線程 oid star
一.currentThread()方法
currentThread方法就是返回當前被調用的線程。
該方法為一個本地方法,原碼如下:
/** * Returns a reference to the currently executing thread object. * * @return the currently executing thread. */ public static native Thread currentThread();
可以看出他返回的是一個線程對象。
下面來看一個列子:
public class CurrentThreadText extendsThread{ public CurrentThreadText(){ System.out.println("構造器被"+Thread.currentThread().getName()+"線程調用了"); } @Override public void run(){ System.out.println("run方法被"+Thread.currentThread().getName()+"線程調用了"); } public static void main(String[] args) { System.out.println("main方法被"+Thread.currentThread().getName()+"線程調用了"); CurrentThreadText cu=new CurrentThreadText(); cu.start(); } }
結果如下:
除了run方法是在一個被自動取名為Thread-0的線程中其他的兩個都在main方法中。
但是我們不使用start方法來啟動線程,我們直接調用run方法會怎麽樣呢?
代碼如下:
public static void main(String[] args) { System.out.println("main方法被"+Thread.currentThread().getName()+"線程調用了"); CurrentThreadText cu=new CurrentThreadText(); cu.run();//我直接調用了run方法 }
結果:
結果都是被main這個線程調用了,所以說想要啟動多線程,就必須使用start方法而不是run方法。run方法就是和單線程一樣按著順序來調用,都在一個main線程中。
二.isAlive()方法
isAlive()方法人如其名意思就是“死沒死啊?”,判斷線程是否處於活躍狀態
列子如下:
public class IsAliveText extends Thread{ @Override public void run(){ System.out.print("調用run這個方法的線程為"+this.getName()); if(this.isAlive()){ System.out.println("這個線程是活躍的"); }else{ System.out.println("這個線程是不活躍的"); } } public static void main(String[] args) { IsAliveText is=new IsAliveText(); System.out.printf(String.format("開始時當前線程為%s,%s", is.getName(),is.isAlive()?("活躍"):("不活躍"))); System.out.println(); is.start(); System.out.printf(String.format("結束時當前線程為%s,%s", is.getName(),is.isAlive()?("活躍"):("不活躍"))); System.out.println(); } }
結果如下:
三.sleep()方法
sleep(n)方法是指讓某個線程睡眠n個毫秒,比如
public class ThreadSleepText { public static void main(String[] args) throws Exception { System.out.println("當前線程為"+Thread.currentThread().getName()); Thread.sleep(5000); System.out.println("結束"); } }
程序會在5秒後結束。
四.getID()方法
過得線程的唯一標識
Java多線程入門中幾個常用的方法