线程问题—一个线程怎么调出另外一个线程的结果。
生活随笔
收集整理的這篇文章主要介紹了
线程问题—一个线程怎么调出另外一个线程的结果。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
問題:建兩線程,線程1進行計算1*1+~+99*99,線程2打印出線程1名字,每隔段時間讀取一次線程1的計算結果?
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的作用!記住,下次將寫出,請大家多提提建議,謝謝!
轉載于:https://www.cnblogs.com/teng-IT/p/4441279.html
總結
以上是生活随笔為你收集整理的线程问题—一个线程怎么调出另外一个线程的结果。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java异常处理和常用类
- 下一篇: Visual Studio 2010 将