问题:建两线程,线程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的作用!记住,下次将写出,请大家多提提建议,谢谢!