//線程同步練習public class ThreadNoSynchronized { public static void main(String argv[ ]){ ShareData oShare = new ShareData();//建立,初始化 ShareData 對象 oShare ThreadDemo th1 = new ThreadDemo("Thread1",oShare);//建立線程 th1 ThreadDemo th2 = new ThreadDemo("Thread2",oShare);//建立線程 th2 th1.start();//啟動線程 th1 th2.start();//啟動線程 th2 }}class ShareData{ public static String szData = "";//聲明,並初始化字串資料域,作為共用資料}class ThreadDemo extends Thread{ private ShareData oShare;//聲明,並初始化 ShareData 資料域 ThreadDemo(){}//聲明,並實現 ThreadDemo 構造方法 //聲明,並實現 ThreadDemo 帶參數的構造方法 ThreadDemo(String szName,ShareData oShare){ super(szName);//調用父類的構造方法 this.oShare = oShare;//初始化 oShare 域 } @SuppressWarnings("static-access")public void run(){ //synchronized (oShare) { //加上本行代碼,實現線程同步,線程有序執行 //不加上面代碼為線程非同步,會出現“線程賽跑”現象 for (int i = 0; i < 5; i++){ if (this.getName().equals("Thread1")){ oShare.szData = "這是第 1 個線程"; //為了示範產生的問題,這裡設定一次睡眠 try{ Thread.sleep((int)Math.random() * 100);//休眠 } catch(InterruptedException e){//捕獲異常 e.printStackTrace(); } System.out.println(this.getName() + ":" + oShare.szData); //輸出字串資訊 }else if(this.getName().equals("Thread2")){ oShare.szData = "這是第 2 個線程"; //為了示範產生的問題,這裡設定一次睡眠 try{ Thread.sleep((int)Math.random() * 100); //線程休眠 }catch(InterruptedException e){//捕獲異常 e.printStackTrace(); } System.out.println(this.getName() + ":" + oShare.szData); //輸出字串資訊 } } //} }}
//線程優先順序練習public class ThreadPriority{ public static void main(String args[ ]){ //用 Thread 類的子類建立線程 InheritThread itd=new InheritThread(); //用 Runnable 介面類的對象建立線程 Thread rtd=new Thread(new RunnableThread()); itd.setPriority(5);//設定 myThread1 的優先順序 5 rtd.setPriority(5);//設定 myThread2 的優先順序 5 itd.start();//啟動線程 itd rtd.start();//啟動線程 rtd }}//設定線程優先順序class InheritThread extends Thread { //自訂線程的 run()方法 public void run(){ System.out.println("我是InheritThread");//輸出字串資訊 for(int i=0;i<10;i++){ System.out.println(" InheritThread: i="+i);//輸出資訊 try{ Thread.sleep((int)Math.random()*1000); //線程休眠,休眠時間為1000內的隨機數 } catch(InterruptedException e)//捕獲異常 {} } }}//通過 Runnable 介面建立的另外一個線程class RunnableThread implements Runnable{ //自訂線程的 run()方法 public void run(){ System.out.println("我是RunnableThread");//輸出字串資訊 for(int i=0;i<10;i++){ System.out.println("RunnableThread : i="+i);//輸出 i try{ Thread.sleep((int)Math.random()*1000);//線程休眠,休眠時間為1000內的隨機數 } catch(InterruptedException e){//捕獲異常 } } }}
/* 多線程之間通訊本例子 類比了生產者和消費者的關係。開始消費者調用消費方法時處於等待狀態,此時喚起生產者線程。生產者開始生產共用資料之後,消費者進行消費,但是當共用資料為空白,所有消費者必須等待,生產者繼續生產,然後消費者再次消費,如此迴圈直到程式運行最後,可以看到線程一直等待。注意這個線程進入等待後沒有其他線程喚醒,除非強行退出 JVM 環境,否則它一直等待。注意:考慮到程式的安全性,多數情況下使用 notifiAll(),除非明確可以知道喚醒哪一個線程。wait 方法調用的前提條件是當前線程擷取了這個對象的鎖,也就是說 wait 方法必須放在同步塊或同步方法中。 */public class ThreadCommunication{ public static void main(String[ ] args){ Queue q = new Queue();//建立,並初始化一個隊列 Producer p = new Producer(q); //建立,並初始化一個生產者 Consumer c = new Consumer(q); //建立,並初始化一個消費者 c.start(); //消費者線程啟動 p.start(); //生產者線程啟動 }}//生產者消費者線程class Producer extends Thread{//實現生產者線程 Queue q;//聲明隊列 qProducer(Queue q){ //生產者構造方法 this.q = q; //隊列 q 初始化}public void run(){ for(int i=1;i<5;i++){ //迴圈添加元素 q.put(i); //給隊列中添加新的元素 }}}class Consumer extends Thread{ Queue q; //聲明隊列 qConsumer(Queue q){ //消費者構造方法 this.q = q; //隊列 q 初始化}public void run(){ while(true){ //迴圈消費元素 q.get(); //擷取隊列中的元素 }}}class Queue{ int value = 0;//聲明,並初始化整數類型資料域 value boolean isEmpty = true;//聲明,並初始化布爾類型資料域 isEmpty,用於判斷隊列的狀態 //生產者生產方法 public synchronized void put(int v){ //如果共用資料沒有被消費,則生產者等待 if (!isEmpty){ try{ System.out.println("生產者等待"); wait();//進入等待狀態 } catch(Exception e){//捕獲異常 e.printStackTrace();//異常資訊輸出 } } value += v;//value 值加 v isEmpty = false;//isEmpty 賦值為 false System.out.println("生產者共生產數量:"+v);//輸出字串資訊 notify();//生產之後通知消費者消費 } //消費者消費的方法 public synchronized int get(){ //消費者消費前,如果共用資料已經被消費完,則消費者等待 if (isEmpty){ try{ System.out.println("消費者等待");//輸出字串資訊 wait();//進入等待狀態 } catch(Exception e){//捕獲異常 e.printStackTrace();//異常資訊輸出 } } value--;//value 值-1 if (value < 1){ isEmpty = true;//isEmpty 賦值 true } System.out.println("消費者消費一個,剩餘:"+value);//輸出資訊 notify();//消費者消費後,通知生產者生產 return value;//返回 value }}