multithreading - How to use java multi-threading properly? -


i many examples in internet there same:

public class test extends thread {     public synchronized void run() {         (int = 0; <= 10; i++) {             system.out.println("i::"+i);         }     }      public static void main(string[] args) {         test obj = new test();          thread t1 = new thread(obj);         thread t2 = new thread(obj);         thread t3 = new thread(obj);          t1.start();         t2.start();         t3.start();     } } 

so why call same task (in run() method) 3 times different threads? e.g. if want upload file, why call 3 times? assume if need multithreading then:

thread t1 task1, e.g.:    - update database info thread t2 task2, e.g.:    - upload file server thread t3 task3, e.g.:    - bring message user 

is there example work described above.

you can create multiple threads code given below start thread , don't need call multiple times same method. can see, once started, 3 child threads share cpu. notice call sleep(10000) in main( ). causes main thread sleep ten seconds , ensures finish last.

     // create multiple threads.          class newthread implements runnable             {                  string name;             } // name of thread thread t;               newthread(string threadname)                {                    name = threadname;               }                t = new thread(this, name);                system.out.println("new thread: " + t);                t.start(); // start thread          }     // entry point thread.         public void run()          {             try              {                  for(int = 5; > 0; i--)                 {                     system.out.println(name + ": " + i);                      thread.sleep(1000);                 }              } catch (interruptedexception e)              {                 system.out.println(name + "interrupted");             }              system.out.println(name + " exiting.");          }     }     class multithreaddemo      {          public static void main(string args[])          {              new newthread("one"); // start threads             new newthread("two");              new newthread("three");         try          {              // wait other threads end             thread.sleep(10000);          }         catch (interruptedexception e)          {              system.out.println("main thread interrupted");          }         system.out.println("main thread exiting.");         }         } 

reference the complete reference herbert schildt


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -