歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 線程的停止

Java 線程的停止

日期:2017/3/1 11:09:39   编辑:Linux編程
  1. class Student implements Runnable
  2. {
  3. public boolean flag=true;
  4. /*public void run() {
  5. while(flag)
  6. {
  7. System.out.println(Thread.currentThread().getName());
  8. }
  9. }*/
  10. public synchronized void run()
  11. {
  12. while(flag)
  13. {
  14. try {
  15. wait();
  16. System.out.println(Thread.currentThread().getName());
  17. }catch(Exception ex)
  18. {
  19. System.out.println(Thread.currentThread().getName()+".......Exception");
  20. flag=false;
  21. }
  22. }
  23. }
  24. }
  25. public class StopThread {
  26. public static void main(String args[])
  27. {
  28. Student stu=new Student();
  29. Thread t1=new Thread (stu);
  30. Thread t2=new Thread(stu);
  31. t1.start();
  32. t2.start();
  33. for(int i=0;i<100;i++)
  34. {
  35. System.out.println(Thread.currentThread().getName());
  36. stu.flag=false;
  37. t1.interrupt();
  38. t2.interrupt();
  39. }
  40. }
  41. }
  42. /*
  43. * 線程的停止
  44. * 在多線程中,線程一般都是循環執行的,而線程裡面執行的代碼就是run 方法裡面定義的代碼,如果run 函數運行結束,那麼線程自然結束
  45. * 所以控制線程結束,就是控制run 方法裡面的循環結束,也就是在某一個時刻設置線程運行的開關
  46. *
  47. *
  48. * 而在線程出於wait 狀態下,你盡管改變了狀態,但現在處於wait 狀態,所有該現在就不能結束,那麼要用線程裡面的另一個方法: interrupt,
  49. * interrupt 將清除wait sleep 的狀態,接著運行程序,同時會拋出一個InterruptException ,所以可以在catch捕捉的異常裡面設置 運行開關,而
  50. * 這種方法如果裡面沒有wait,將不會停止線程
  51. *
  52. * 所以由上面兩點得出,要終止現在得有兩點,一是在某一時刻,設置線程的運行開關,而且如果有wait 的話,那麼就用interrupt ,然後捕捉異常,在異常
  53. * 裡面設置 線程運行開關
  54. *
  55. * 2011/10/24 20:49:21
  56. * */
Copyright © Linux教程網 All Rights Reserved