java多執行緒執行問題

weixin_34205076發表於2017-11-15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Demo extends Thread{
    public Demo(String name){
        super(name);
    }
      
    public void run(){
        for(int i=0; i<6; ++i){
            System.out.println("i = " + i + "......Thread=" + Thread.currentThread().getName());
            try{
                Thread.sleep(100);
            }catch(InterruptedException e){
                System.out.println("程式被打斷!");
            }
        }
    }
}
 
 
public class Test{
   public static void main(String[] args) throws InterruptedException{
          
        Demo d1 = new Demo("hjz");
        Demo d2 = new Demo("chb");
        d1.start();
        //另外當某一個執行緒因為異常而終止,其他的執行緒照樣執行,不會受到任何影響!
        System.out.println(5/0);//throw new ArithmeticException()
        for(int i=0; i<6; ++i){
            System.out.println("i = " + i + "......Thread=" + Thread.currentThread().getName());
            Thread.sleep(200);
        }
         
         
        d2.start();//如果開啟新執行緒之前,就因為異常而中止了執行緒,那麼新執行緒將無法開啟!
   }
}
  
/* 
 class Demo extends Thread{
    public Demo(String name){
        super(name);
    }
    //public Thread(String name) {
    //    init(null, null, name, 0);
    //} 也就是在建立執行緒物件的時候,通過建構函式該執行緒就有了名字了!
    public void run(){
        for(int i=0; i<6; ++i){
            System.out.println("i = " + i + "......Thread=" + getName());
            try{
                Thread.sleep(100);
            }catch(InterruptedException e){
                System.out.println("程式被打斷!");
            }
        }
    }
}
 
public class Test{
   public static void main(String[] args) throws InterruptedException{
        Demo d1 = new Demo("hjz");
        Demo d2 = new Demo("chb");
         
        d1.run();
        d2.run();  
   }
}
 */

  










本文轉自 小眼兒 部落格園部落格,原文連結:http://www.cnblogs.com/hujunzheng/p/3871895.html,如需轉載請自行聯絡原作者

相關文章