線程問題—一個線程怎麼調出另一個線程的結果。

 

問題:建兩線程,線程1進行計算1*1+~+99*99,線程2打印出線程1名字,每隔段時間讀取一次線程1的計算結果?this

 1 public class Other{
 2     public static volatile int sum;
 3     public static void main(String[] args){
 4         Thread t1=new ThreadClass();
 5         t1.setName("我是線程1");
 6         Thread t2=new Thread(new RunnableClass(t1.getName()));
 7         t2.setDaemon(true);
 8         t1.start();
 9         t2.start();
10     }
11     static class RunnableClass implements Runnable{
12     private String name;
13     public RunnableClass(String name){
14         this.name=name;
15     }
16     public void run(){
17         while(true){
18                 
19                 try{
20                 System.out.println(name+"  "+sum);
21                 Thread.sleep(3000);
22             }catch (Exception e){
23                 System.out.println(e);
24             }
25         }
26     }
27     
28 }
29 static class ThreadClass extends Thread {
30     public void run (){
31         for(int k=1;k<100;k++){
32             try{sum+=count(k);
33             sleep(1000);}catch(Exception e){
34                 System.out.println(e);
35             }
36         }
37     }
38     public int count(int i){
39         return (i*i);
40         }
41     
42 }
43 }Runnable接口 沒有 Thread 類裏面的方法,因此使用sleep方法時,須要Thread.sleep();記得sleep方法會返回異常,因此要用try來進行異常處理。static的做用!記住,下次將寫出,請你們多提提建議,謝謝! 
相關文章
相關標籤/搜索