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 }
这个例子说明线程是可以传递资源的(资源是一个类实例),这样就可以在线程中调用这个实例的方法。希望大家多提提建议!谢谢撒!