1 Public classjob1{2 Public Static voidMain (string[] args) {3 //threadclass t=new threadclass ();4 //runnableclass r=new runnableclass ();5Sums s=NewSums ();6ThreadClass t1=NewThreadClass (s);7 //thread t1=new Thread (new ThreadClass (s));8Thread r1=NewThread (NewRunnableclass (s));9R1.setdaemon (true);Ten T1.start (); One R1.start (); A } - } - classsums{ the Public intsum; - Public voidcalculate () { - for(inti=1;i<100;i++){ - Try{Thread.Sleep (100); +Sum+=i*i;}Catch(Exception e) { - System.out.println (e); + } A } at } - Public intgetsum () { - returnsum; - } - } - classThreadClassextendsthread{ in PrivateSums S; - PublicThreadClass (Sums s) { to This. s=s; + } - Public voidrun () { the s.calculate (); * } $ }Panax Notoginseng classRunnableclassImplementsrunnable{ - PrivateSums S; the PublicRunnableclass (Sums s) { + This. s=s; A } the Public voidrun () { + for(inti=0;i<100;i++){ - Try{Thread.Sleep (300); $System.out.println (S.getsum ());}Catch(Exception e) { $ System.out.println (e); - } - } the } -}
This example shows that a thread can pass a resource (the resource is an instance of a class), so that it can be called in the process. I hope you will make more suggestions! Thank you, Isaac!
Threading issues-how a thread can invoke the results of another thread (2)