java - Usage of "this" in Thread constructor -


could explain me meaning of "this" in line "th = new thread( this, name);" of following program? thread constructor used thread(runnable threadob, string name). why have use word "this" in above expression? example, in case write "th = new thread( newob, name);", eclipse mentions ob cannot resolved variable. have use "this" in case, , if so, why? many in advance.

class mythread implements runnable{     int count;     thread th;      mythread(string name){         th = new thread( newob, name);         count =0;         th.start();     }      public void run(){         system.out.println(th.getname() + " starting ");         try{             do{                 thread.sleep(500);                 system.out.println(" in " + th.getname() + " count " + count);                 count++;             }while(count<5);         }         catch(interruptedexception e){             system.out.println(e);         }         system.out.println(th.getname() + " terminating");     } } public class usethreads {      public static void main(string[] args) {  system.out.println("main thread");          mythread mt = new mythread("thread1");          do{             system.out.println(".");             try{                 thread.sleep(100);             }             catch(interruptedexception e){                 system.out.println(e);             }         }while(mt.count!=5);          system.out.println("main thread terminating ");     } } 

this represents current object in curent context. this can change based on context. example in run() method if create , instantiate anonymous inner class, inside class, this different this in run() method.

why use when runnable object expected?. have :

class mythread implements runnable{ 

so, in mythread(string name) , current instance of mythread. since mythread implements runnable, mythread instances runnables, so, can used instead of instance of runnable

example :

someobject obj = new someobject(); obj.dosomething();   private void dosomething(){ // here implicitly set obj i.e, calling object }  

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -