Java多線程簡單示例

多線程簡單控制示例。

1. extends Thread.

  1. package cn.com.keke.thread.test;  
  2. /**  
  3.  * extends Thread  
  4.  * @author player  
  5.  *  
  6.  */ 
  7. public class MyThread extends Thread {  
  8.  
  9.     //線程執行條件  
  10.     private boolean t;  
  11.  
  12.     public MyThread(boolean b) {  
  13.         this.t = b;  
  14.     }  
  15.  
  16.     public void run() {  
  17.         if (this.t) {  
  18.             System.out.print(" T ");  
  19.         } else {  
  20.             System.out.print(" F ");  
  21.         }  
  22.     }  
  23.  
  24.     public static void main(String[] args) {  
  25.         Thread t1 = new MyThread(true);  
  26.         Thread t2 = new MyThread(false);  
  27.         t1.start();  
  28.         t2.start();  
  29.           
  30.         // Thread 成員變量threadStatus 作怪  
  31. //      int i = 0;  
  32. //      do {  
  33. //          t1.start(); //throw runtime exception  
  34. //          t2.start(); //throw runtime exception  
  35.           
  36. //          new Thread(t1).start(); //line is ok  
  37. //          new Thread(t2).start(); // line is ok  
  38. //          i++;  
  39. //      } while (i < 5);  
  40.     }  

2 implements Runnable.

  1. package cn.com.keke.thread.test;  
  2. /**  
  3.  * implements Runnable  
  4.  * @author player  
  5.  *  
  6.  */ 
  7. public class MyThread2 implements Runnable {  
  8.  
  9.     private boolean t;  
  10.  
  11.     public MyThread2(boolean b) {  
  12.         this.t = b;  
  13.     }  
  14.  
  15.     public void run() {  
  16.         if (t) {  
  17.             System.out.print(" T ");  
  18.         } else {  
  19.             System.out.print(" F ");  
  20.         }  
  21.     }  
  22.  
  23.     public static void main(String[] args) {  
  24.         MyThread2 t1 = new MyThread2(true);  
  25.         MyThread2 t2 = new MyThread2(false);  
  26.  
  27.         Thread tt1 = new Thread(t1);  
  28.         Thread tt2 = new Thread(t2);  
  29.  
  30.         tt1.start();  
  31.         tt2.start();  
  32.           
  33. //      // Thread threadStatus 作怪  
  34. //      int i = 0;  
  35. //      do {  
  36. //          tt1.start();//throw runtime exception  
  37. //          tt2.start();//throw runtime exception  
  38. //            
  39. //          new Thread(t1).start();//line is ok  
  40. //          new Thread(t2).start();//line is ok  
  41. //          i++;  
  42. //      } while (i < 5);  
  43. //  }  
  44.  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章