Java 线程实例一(查看线程是否存活、获取当前线程名称、状态监测、线程优先级设置、死锁及解决方法、获取线程id、线程挂起)
查看線程是否存活
以下實例演示了如何通過繼承 Thread 類并使用 isAlive() 方法來檢測一個線程是否存活:
public class TwoThreadAlive extends Thread {public void run() {for (int i = 0; i < 10; i++) {printMsg();}}public void printMsg() {Thread t = Thread.currentThread();String name = t.getName();System.out.println("name=" + name);}public static void main(String[] args) {TwoThreadAlive tt = new TwoThreadAlive();tt.setName("Thread");System.out.println("before start(), tt.isAlive()=" + tt.isAlive());tt.start();System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());for (int i = 0; i < 10; i++) {tt.printMsg();}System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());} }以上代碼運行輸出結果為:
before start(), tt.isAlive()=false just after start(), tt.isAlive()=true name=main name=Thread name=main name=main name=main name=main name=main name=main name=main name=main name=main name=Thread name=Thread name=Thread name=Thread name=Thread The end of main(), tt.isAlive()=true name=Thread name=Thread name=Thread name=Thread?
獲取當前線程名稱
以下實例演示了如何通過繼承 Thread 類并使用 getName() 方法來獲取當前線程名稱:
public class TwoThreadGetName extends Thread {public void run() {for (int i = 0; i < 10; i++) {printMsg();}}public void printMsg() {Thread t = Thread.currentThread();String name = t.getName();System.out.println("name=" + name);} public static void main(String[] args) {TwoThreadGetName tt = new TwoThreadGetName();tt.start();for (int i = 0; i < 10; i++) {tt.printMsg();}} }以上代碼運行輸出結果為:
name=main name=main name=main name=main name=main name=Thread-0 name=Thread-0 name=Thread-0 name=Thread-0 name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0 name=main name=Thread-0?
狀態(tài)監(jiān)測
以下實例演示了如何通過繼承 Thread 類并使用 currentThread.getName() 方法來監(jiān)測線程的狀態(tài):
class MyThread extends Thread{boolean waiting= true;boolean ready= false;MyThread() {}public void run() {String thrdName = Thread.currentThread().getName();System.out.println(thrdName + " starting.");while(waiting) System.out.println("waiting:"+waiting); System.out.println("waiting...");startWait(); try {Thread.sleep(1000);}catch(Exception exc) {System.out.println(thrdName + " interrupted.");}System.out.println(thrdName + " terminating.");}synchronized void startWait() {try {while(!ready) wait();}catch(InterruptedException exc) {System.out.println("wait() interrupted");}}synchronized void notice() {ready = true;notify();} } public class Main {public static void main(String args[]) throws Exception{MyThread thrd = new MyThread();thrd.setName("MyThread #1");showThreadStatus(thrd);thrd.start();Thread.sleep(50);showThreadStatus(thrd);thrd.waiting = false;Thread.sleep(50); showThreadStatus(thrd);thrd.notice();Thread.sleep(50);showThreadStatus(thrd);while(thrd.isAlive()) System.out.println("alive");showThreadStatus(thrd);}static void showThreadStatus(Thread thrd) {System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());} }以上代碼運行輸出結果為:
…… alive alive MyThread #1 terminating. alive ……?
線程優(yōu)先級設置
以下實例演示了如何通過setPriority() 方法來設置線程的優(yōu)先級:
public class SimplePriorities extends Thread {private int countDown = 5;private volatile double d = 0; public SimplePriorities(int priority) {setPriority(priority);start();}public String toString() {return super.toString() + ": " + countDown;}public void run() {while(true) {for(int i = 1; i < 100000; i++)d = d + (Math.PI + Math.E) / (double)i;System.out.println(this);if(--countDown == 0) return;}}public static void main(String[] args) {new SimplePriorities(Thread.MAX_PRIORITY);for(int i = 0; i < 5; i++)new SimplePriorities(Thread.MIN_PRIORITY);} }以上代碼運行輸出結果為:
Thread[Thread-1,1,main]: 5 Thread[Thread-2,1,main]: 5 Thread[Thread-3,1,main]: 5 Thread[Thread-0,10,main]: 5 Thread[Thread-3,1,main]: 4 Thread[Thread-0,10,main]: 4 Thread[Thread-1,1,main]: 4 Thread[Thread-5,1,main]: 5 Thread[Thread-4,1,main]: 5 Thread[Thread-2,1,main]: 4 Thread[Thread-0,10,main]: 3 Thread[Thread-1,1,main]: 3 Thread[Thread-4,1,main]: 4 Thread[Thread-2,1,main]: 3 ……?
死鎖及解決方法
死鎖是這樣一種情形:多個線程同時被阻塞,它們中的一個或者全部都在等待某個資源被釋放。由于線程被無限期地阻塞,因此程序不可能正常終止。
java 死鎖產生的四個必要條件:
- 1、互斥使用,即當資源被一個線程使用(占有)時,別的線程不能使用
- 2、不可搶占,資源請求者不能強制從資源占有者手中奪取資源,資源只能由資源占有者主動釋放。
- 3、請求和保持,即當資源請求者在請求其他的資源的同時保持對原有資源的占有。
- 4、循環(huán)等待,即存在一個等待隊列:P1占有P2的資源,P2占有P3的資源,P3占有P1的資源。這樣就形成了一個等待環(huán)路。
當上述四個條件都成立的時候,便形成死鎖。當然,死鎖的情況下如果打破上述任何一個條件,便可讓死鎖消失。下面用java代碼來模擬一下死鎖的產生。
解決死鎖問題的方法是:一種是用synchronized,一種是用Lock顯式鎖實現(xiàn)。
而如果不恰當?shù)氖褂昧随i,且出現(xiàn)同時要鎖多個對象時,會出現(xiàn)死鎖情況,如下:
import java.util.Date;public class LockTest {public static String obj1 = "obj1";public static String obj2 = "obj2";public static void main(String[] args) {LockA la = new LockA();new Thread(la).start();LockB lb = new LockB();new Thread(lb).start();} } class LockA implements Runnable{public void run() {try {System.out.println(new Date().toString() + " LockA 開始執(zhí)行");while(true){synchronized (LockTest.obj1) {System.out.println(new Date().toString() + " LockA 鎖住 obj1");Thread.sleep(3000); // 此處等待是給B能鎖住機會synchronized (LockTest.obj2) {System.out.println(new Date().toString() + " LockA 鎖住 obj2");Thread.sleep(60 * 1000); // 為測試,占用了就不放}}}} catch (Exception e) {e.printStackTrace();}} } class LockB implements Runnable{public void run() {try {System.out.println(new Date().toString() + " LockB 開始執(zhí)行");while(true){synchronized (LockTest.obj2) {System.out.println(new Date().toString() + " LockB 鎖住 obj2");Thread.sleep(3000); // 此處等待是給A能鎖住機會synchronized (LockTest.obj1) {System.out.println(new Date().toString() + " LockB 鎖住 obj1");Thread.sleep(60 * 1000); // 為測試,占用了就不放}}}} catch (Exception e) {e.printStackTrace();}} }以上代碼運行輸出結果為:
Tue May 05 10:51:06 CST 2015 LockB 開始執(zhí)行 Tue May 05 10:51:06 CST 2015 LockA 開始執(zhí)行 Tue May 05 10:51:06 CST 2015 LockB 鎖住 obj2 Tue May 05 10:51:06 CST 2015 LockA 鎖住 obj1此時死鎖產生。
為了解決這個問題,我們不使用顯示的去鎖,我們用信號量去控制。
信號量可以控制資源能被多少線程訪問,這里我們指定只能被一個線程訪問,就做到了類似鎖住。而信號量可以指定去獲取的超時時間,我們可以根據(jù)這個超時時間,去做一個額外處理。
對于無法成功獲取的情況,一般就是重復嘗試,或指定嘗試的次數(shù),也可以馬上退出。
來看下如下代碼:
import java.util.Date; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit;public class UnLockTest {public static String obj1 = "obj1";public static final Semaphore a1 = new Semaphore(1);public static String obj2 = "obj2";public static final Semaphore a2 = new Semaphore(1);public static void main(String[] args) {LockAa la = new LockAa();new Thread(la).start();LockBb lb = new LockBb();new Thread(lb).start();} } class LockAa implements Runnable {public void run() {try {System.out.println(new Date().toString() + " LockA 開始執(zhí)行");while (true) {if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {System.out.println(new Date().toString() + " LockA 鎖住 obj1");if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {System.out.println(new Date().toString() + " LockA 鎖住 obj2");Thread.sleep(60 * 1000); // do something}else{System.out.println(new Date().toString() + "LockA 鎖 obj2 失敗");}}else{System.out.println(new Date().toString() + "LockA 鎖 obj1 失敗");}UnLockTest.a1.release(); // 釋放UnLockTest.a2.release();Thread.sleep(1000); // 馬上進行嘗試,現(xiàn)實情況下do something是不確定的}} catch (Exception e) {e.printStackTrace();}} } class LockBb implements Runnable {public void run() {try {System.out.println(new Date().toString() + " LockB 開始執(zhí)行");while (true) {if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {System.out.println(new Date().toString() + " LockB 鎖住 obj2");if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {System.out.println(new Date().toString() + " LockB 鎖住 obj1");Thread.sleep(60 * 1000); // do something}else{System.out.println(new Date().toString() + "LockB 鎖 obj1 失敗");}}else{System.out.println(new Date().toString() + "LockB 鎖 obj2 失敗");}UnLockTest.a1.release(); // 釋放UnLockTest.a2.release();Thread.sleep(10 * 1000); // 這里只是為了演示,所以tryAcquire只用1秒,而且B要給A讓出能執(zhí)行的時間,否則兩個永遠是死鎖}} catch (Exception e) {e.printStackTrace();}} }以上實例代碼輸出結構為:
Tue May 05 10:59:13 CST 2015 LockA 開始執(zhí)行 Tue May 05 10:59:13 CST 2015 LockB 開始執(zhí)行 Tue May 05 10:59:13 CST 2015 LockB 鎖住 obj2 Tue May 05 10:59:13 CST 2015 LockA 鎖住 obj1 Tue May 05 10:59:14 CST 2015LockB 鎖 obj1 失敗 Tue May 05 10:59:14 CST 2015LockA 鎖 obj2 失敗 Tue May 05 10:59:15 CST 2015 LockA 鎖住 obj1 Tue May 05 10:59:15 CST 2015 LockA 鎖住 obj2?
獲取線程id
以下實例演示了如何使用 getThreadId() 方法獲取線程id:
public class Main extends Object implements Runnable {private ThreadID var;public Main(ThreadID v) {this.var = v;}public void run() {try {print("var getThreadID =" + var.getThreadID());Thread.sleep(2000);print("var getThreadID =" + var.getThreadID());} catch (InterruptedException x) {}}private static void print(String msg) {String name = Thread.currentThread().getName();System.out.println(name + ": " + msg);}public static void main(String[] args) {ThreadID tid = new ThreadID();Main shared = new Main(tid);try {Thread threadA = new Thread(shared, "threadA");threadA.start();Thread.sleep(500);Thread threadB = new Thread(shared, "threadB");threadB.start();Thread.sleep(500);Thread threadC = new Thread(shared, "threadC");threadC.start();} catch (InterruptedException x) {}} }class ThreadID extends ThreadLocal {private int nextID;public ThreadID() {nextID = 10001;}private synchronized Integer getNewID() {Integer id = new Integer(nextID);nextID++;return id;}protected Object initialValue() {print("in initialValue()");return getNewID();}public int getThreadID() {Integer id = (Integer) get();return id.intValue();}private static void print(String msg) {String name = Thread.currentThread().getName();System.out.println(name + ": " + msg);} }以上代碼運行輸出結果為:
threadA: in initialValue() threadA: var getThreadID =10001 threadB: in initialValue() threadB: var getThreadID =10002 threadC: in initialValue() threadC: var getThreadID =10003 threadA: var getThreadID =10001 threadB: var getThreadID =10002 threadC: var getThreadID =10003?
線程掛起
public class SleepingThread extends Thread {private int countDown = 5;private static int threadCount = 0;public SleepingThread() {super("" + ++threadCount);start();}public String toString() { return "#" + getName() + ": " + countDown;}public void run() {while (true) {System.out.println(this);if (--countDown == 0)return;try {sleep(100);}catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 5; i++)new SleepingThread().join();System.out.println("線程已被掛起");} }以上代碼運行輸出結果為:
#1: 5 #1: 4 #1: 3 #1: 2 #1: 1 …… #5: 3 #5: 2 #5: 1 線程已被掛起?
總結
以上是生活随笔為你收集整理的Java 线程实例一(查看线程是否存活、获取当前线程名称、状态监测、线程优先级设置、死锁及解决方法、获取线程id、线程挂起)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker 的4种网络模式
- 下一篇: java美元兑换,(Java实现) 美元