Problem: Two threads are built, thread 1 is computed 1*1+~+99*99, thread 2 prints the outgoing thread 1 name, and reads the calculation results of threads 1 at intervals?
1 Public classother{2 Public Static volatile intsum;3 Public Static voidMain (string[] args) {4Thread t1=NewThreadClass ();5T1.setname ("I am thread 1");6Thread t2=NewThread (NewRunnableclass (T1.getname ()));7T2.setdaemon (true);8 T1.start ();9 T2.start ();Ten } One Static classRunnableclassImplementsrunnable{ A PrivateString name; - PublicRunnableclass (String name) { - This. name=name; the } - Public voidrun () { - while(true){ - + Try{ -System.out.println (name+ "" +sum); +Thread.Sleep (3000); A}Catch(Exception e) { at System.out.println (e); - } - } - } - - } in Static classThreadClassextendsThread { - Public voidrun () { to for(intk=1;k<100;k++){ + Try{sum+=count (k); -Sleep (1000);}Catch(Exception e) { the System.out.println (e); * } $ }Panax Notoginseng } - Public intCountinti) { the return(i*i); + } A the } +}
The runnable interface does not have a method inside the Thread class, so when you use the Sleep method, you need to Thread.Sleep (); Remember that the Sleep method returns an exception, so use try to do the exception handling. The effect of static! Remember, next time will be written, please give more suggestions, thank you!
Threading issues-how one thread pulls out the result of another thread.