java - Calling functions from threads -


i beginner in java. have been studying multithreading. want create 2 threads , these 2 threads must run separate methods concurrently. here these threads should call sum , diff method , run simultaneously. getting error, method should of thread type. how achieve it.

class demo implements runnable  {     void  sum()     {       //some lines of code     }      void  diff()     {       //some lines of code     }             public void run ()     {        system.out.println("inside run");     }   }    class test  {     public static void main (string []args){         demo o = new demo ();         demo o1 = new demo ();         thread th = new thread (o);         thread th1= new thread(o1);         th.start();         th1.start();         o.th.sum();  // getting error here         o1.th1.diff(); // getting error here     } } 

first of have compilation error because you're trying reference variable th field on object of type demo. th not field, rather local variable , can referenced directly (i.e. without o. prefix). second, sum() , diff() cannot called against instance of thread methods not defined thread, rather own demo class.

all being said, these compilation problems aren't root issue code. based on code seems have fundamental misunderstandings syntax , structure of java programs might benefit go through entry-level tutorials before trying tackle concurrent programming. but, sake of completeness here brief explanation of need in order make program work.

when call thread.start() it's going fork thread , call run() method of runnable passed thread object's constructor.

in order call 2 different methods need create 2 different classes implement runnable , put 2 method implementations in each of run methods.

example:

public class sum implements runnable {    public void run() {       //add numbers    } }  public class diff implements runnable {    public void run() {       //subtract numbers    } }   public class test {    public static void main(string[] args) {       thread sumthread = new thread(new sum());       thread diffthread = new thread(new diff());       sumthread.start();       diffthread.start();    } } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -