線程問題-一個線程怎麼調用另外一個線程的結果(2)

 1 public class Job1{
 2     public static void main(String[] args){
 3         //ThreadClass t=new ThreadClass();
 4         //RunnableClass r=new RunnableClass();
 5         Sums s=new Sums();
 6         ThreadClass t1=new ThreadClass(s);
 7         //Thread t1=new Thread(new ThreadClass(s));
 8         Thread r1=new Thread(new RunnableClass(s));
 9         r1.setDaemon(true);
10         t1.start();
11         r1.start();
12     }
13 }
14 class Sums{
15     public int sum;
16     public void calculate(){
17         for(int i=1;i<100;i++){
18             try{Thread.sleep(100);
19             sum+=i*i;}catch(Exception e){
20                 System.out.println(e);
21             }
22         }
23     }
24     public int getSum(){
25         return sum;
26     }
27 }
28 class ThreadClass extends Thread{
29     private Sums s;
30     public ThreadClass(Sums s){
31         this.s=s;
32     }
33     public void run(){
34         s.calculate();
35     }
36 }
37 class RunnableClass implements Runnable{
38     private Sums s;
39     public RunnableClass (Sums s){
40         this.s=s;
41     }
42     public void run(){
43     for(int i=0;i<100;i++){
44         try{Thread.sleep(300);
45         System.out.println(s.getSum());}catch(Exception e){
46             System.out.println(e);
47         }
48     }
49     }
50 }

這個例子說明線程是能夠傳遞資源的(資源是一個類實例),這樣就能夠在線程中調用這個實例的方法。但願你們多提提建議!謝謝撒!this

相關文章
相關標籤/搜索