3 Replies - 3141 Views - Last Post: 24 March 2013 - 05:41 AM Rate Topic: -----

#1 joshuajobin08   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-September 12

explain this keyword in Thread

Posted 24 March 2013 - 05:09 AM

why this is used in the below program. I am not able to understand the use of it.When i remove that this keyword my output is not displayed. While when i write ,it displays the output.
import java.io.*;
class printmsg{
    synchronized void printmember(int n){
        try{
            System.out.println("start");
            for(int j=n;j>0;j--){
                if(j==n/2)
                    Thread.sleep(10);
                System.out.println(j);
            }
            System.out.println("end");
        }
        catch(Exception e){

            System.out.println(e);}
    }
}
class demo implements Runnable{
    int n;
    printmsg pt=new printmsg();
    Thread th=new Thread(this);
    demo(printmsg p,int x){
        pt=p;
        n=x;

        th.start();
    }
    public void run(){
        pt.printmember(n);
    }
}
class demo3{
    public static void main(String args[]){
        printmsg p=new printmsg();
        demo d1=new demo(p,16);
        demo d2=new demo(p,8);
        demo d3=new demo(p,10);

    }
}



i am having doubt in this part.
Thread th=new Thread(this);


i mean "this" keyword why it is used.

i mean "this" keyword why it is used.

This post has been edited by GregBrannon: 24 March 2013 - 05:08 AM
Reason for edit:: Indented the code - makes it easier to read.


Is This A Good Question/Topic? 0
  • +

Replies To: explain this keyword in Thread

#2 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: explain this keyword in Thread

Posted 24 March 2013 - 05:39 AM

Within the class demo (should be capitalized - Demo) this refers to the current instance of this class. You pass this instance to the Thread() constructor, and the instance contains a single method run(), which contains the code to run within the Thread.
Was This Post Helpful? 0
  • +
  • -

#3 darek9576   User is offline

  • D.I.C Lover

Reputation: 204
  • View blog
  • Posts: 1,740
  • Joined: 13-March 10

Re: explain this keyword in Thread

Posted 24 March 2013 - 05:39 AM

new Thread() is a constructor, so check out API and have a look what arguments it takes.
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: explain this keyword in Thread

Posted 24 March 2013 - 05:41 AM

http://docs.oracle.c.../runthread.html
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1