Creating thread by extending thread class?

HI
What is the differnce in run() method in the thread class and
public void run() method in ruble interface is both are same or saparete?
is the run() method in the Thread class overridden method from Runnable interface?
Thns

It's a difference in paradigm. If you are changing the behaviour of how Thread works, extend from Thread.
If you're implementing a system where you're using Thread instances to control some process, implement Runnable.
In the vast majority of cases, that means you'll be implementing Runnable.
The exception might be if you're writing an application server, or a process manager of some sort.

Similar Messages

  • Creating array of objects of class which extends Thread

    getting NullPointerException
    can i not create thread array this way?
    class sample extends Thread
    { int i,id;
      public sample(int c)
       { id=c;
      public void run()
      { for(i=0;i<6;i++)
         System.out.println("Thread "+id+" "+i);
    public class thread extends Frame implements ActionListener
    {  Button b1;
       sample s[];
       thread()
       { for(int i=0;i<2;i++)
              s=new sample(i);
         setLayout(new FlowLayout());
         b1=new Button("OK");
         add(b1);
         b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
         {   b1.setEnabled(false);
              for(int i=0;i<2;i++)
              { s[i]=new sample(i);
              s[i].start();
         public static void main(String args[])
         { thread t1=new thread(); 
         t1.setVisible(true);
         t1.setSize(150,150);

    You need:
    sample [] s = new sample[2];However
    1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
    2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that.

  • Extending the Thread class

    i would like to do that
    1) One thread displays "ABC" every 2 second;
    2) The other thread displays DEF every 5 seconds;
    i need to create the threads by extending the Thread class ...
    thank you for your help ,
                public class Thread1 extends Thread {
              public Thread1(String s ) {
                   super (s);
              public void run() {
                   for ( int i=0; i<5; i++ ) {
                        System.out.println(getName());
                        try {
                           sleep ((long) 5000);
                        } catch (InterruptedException e ) {
                           /* do nothing */
              public static void main (String args[]) {
                   new Thread1 ("ABC").start();
                   new Thread1 ("DEF").start();
         }     

    I think he has been told to use the Thread class by the sounds of it.
    public class Thread1 extends Thread {
         public Thread1(String s ) {
              super (s);
         public void run() {
              for ( int i=0; i<5; i++ ) {
                   System.out.println(getName());
                   try {
                      sleep (getName().equals("ABC")? 5000 : 2000); //If you don't understand this then Google for "Java ternary operator"
                   } catch (InterruptedException e ) {
                      /* do nothing */
         public static void main (String args[]) {
              new Thread1 ("ABC").start();
              new Thread1 ("DEF").start();
    }

  • Implementing Runnable interface  Vs  extending Thread class

    hi,
    i've come to know by some people says that Implementing Runnbale interface while creating a thread is better option rather than extending a Thread class. HOw and Why? Can anybody explain.?

    Its the same amount of programming work...
    Sometimes it is not possible to extend Thread, becuase your threaded class might have to extend something else.
    The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
    http://developerlife.com/lessons/threadsintro/default.htm#Implementing

  • Listeners, load a class on startup and creating threads in infinite loop

    This is an identical post to the one I made in the jsp forum. I do this as I know, being a regular here, that there are equally good people(in j2ee web application development) in both these forum, but many of them stick to their particular forums of choice - jsp / servlets.
    I was wondering if there is any means by which I could launch my own class when tomcat starts (in the same jvm).
    1. I need one or more Thread/TimerTask because the requirement is such that the application would have continous data drops (in the form of logs) which has to be picked up, parsed and pushed into a db. Another part of the application reads the data from the db on requests (http) and displays it over the web. The thread has to poll for arrival of new logs and then hand it over to a framework for parsing and inserting the parsed data to a db.
    2. I know that I can possibly use a servlet with a load-on-startup value greater than 1 and code my requirement into the init method. However, using a servlet for a functionality different from servicing http requests has me worried. (valid ?), not to mention the fact that Iam very uneasy about creating threads from within Servlets.
    3. I googled hard and found that I could probably use a tomcat specific context lifecycle listener.
    4. I could also possibly use the servlet api - the ServletContextListener.
    5. I have rejected #2 and settled on either #3 or #4 - the ServletContextListener or Tomcat specific Lifecycle Listener, though the later, as I said binds me to Tomcat (which is ok for me). Are there any other specific (dis)advantages of using either especially when I have to create threads from within them (on context startup)? Other than memory leaks, killing the thread objects & associated resources on context shutdown, is there anything else that I need to watch out for while using threads.
    6. I wonder is there is there a plain startup hook available in tomcat (rather than listeners) - from where I can launch a class that starts a thread in the same jvm as tomcat's ?
    Thanks In Advance,
    Ram.

    Anybody ? Sorry for bumping up.
    Thanks,
    Ram.

  • Unable to create thread from startup class

    Hi,
    We are trying to create thread from our scheduler class. This scheduler class
    is called from a Startup class configured in WebLogic 7. But we failed to create
    thread. It does not showing any error also. Can anyone plz suggest what could
    be the problem.
    Thanks & Regards,
    Siddhartha

    Hi,
    We are trying to create thread from our scheduler class. This scheduler class
    is called from a Startup class configured in WebLogic 7. But we failed to create
    thread. It does not showing any error also. Can anyone plz suggest what could
    be the problem.
    Thanks & Regards,
    Siddhartha

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • Connecting to database in a thread class

    HI,
    I am have a problem when trying to get a conneciton to a database. I am trying to create the connection in a class that extends Thread.
    Everythign else is set up correctly, i have ran the same code from the main class of my project and it works fine, the problem occurs when I try to get the connection from the class spawned by the main class.
    The exception thrown is an SQL exception: No suitable driver found, however the driver was loaded previously (no class not found exception was thrown when loading).
    The only reason I can think of that coudl be causing a problem is the fact the class creating the connection extends thread and runs in the run method i.e. a different thread.
    Does anybody know of any issues regarding threads and JDBC?
    NOTE: I and using the COM.ibm.db2.jdbc.net.DB2Driver for connecting to DB2.
    Cheers :)

    Here is the output
    Driver loaded
    Authorising for: test - testpass
    Protocol connecting to database
    Exception in Protocol: java.sql.SQLException: No suitable driver
    java.sql.SQLException: No suitable driver
         at java.sql.DriverManager.getConnection(DriverManager.java:532)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at baeauthserver.AuthProtocol.getPMConnection(AuthProtocol.java:66)
         at baeauthserver.AuthServerThread.run(AuthServerThread.java:38)The program is a server daemon or service that listens for connections from a client. On connection the server spawns a "work" thread to deal with authorising the user and creating a database connection. I can make a connection in the main server class (i.e. the main thread) but as soon as I move this to the "work" class it seems to lose the driver.
    I've just done some more tests and I can't even grab the driver as a driver object on the work thread so it's not just the getConnection method.
    I'm initialising the driver in a static block in the main server program. I've moved it around to various constructors on both the main class and the work class to no avail.
    It has me stumped so far :p
    Thanks for the input though :)

  • Unable to create thread

    i wrote a code of a multiclient server ,but when i compile it i can't see any window opening nor ant thread class is being created.... please help
    SERVER:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    public class MultiThreadedServer3 extends JFrame implements Runnable {
        private JTextArea jta = new JTextArea();
        public  Vector v;
        String messageReceived;
        BufferedReader inputFromClient = null;
        PrintWriter outputToClient = null;
        String client_name = null;
        public int z;
        Thread t = null;
        Socket socket = null;
        /** Creates a new instance of MultiThreadSimpleServer */
        public void MultiThreadedServer3() {
            // place text area on the frame
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
            setTitle("Simple Server");
            setSize(500, 300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            jta.setEditable(false);
            try {
                ServerSocket serverSocket = new ServerSocket(4242);
                System.out.println("Server is upp and running");
                jta.append("Server started at " + new Date() + "\n");
                while (true) {
                  socket = serverSocket.accept(); // accept connections
                InetAddress inetAddress = socket.getInetAddress(); // used to get host information
                /* Get host IP and hostname and display on the window */
                jta.append("Client connected to the server!\n" +
                         "\n" +
                        "Client's IP Address is: " + inetAddress.getHostAddress() + "\n");
                // Create a new thread for connection
                v = new Vector();
                t = new Thread(this); // create a new thread
                t.start();
            catch (IOException ex) {
                System.err.println(ex);
        } //close MiultiThreaddeServer3();
            synchronized public void send()
                    throws IOException
                outputToClient.println(messageReceived);
            synchronized public void send_personal()
                    throws IOException
            {   /* to get the position of the person's name
                 * with whom the client wants to cummunicate
                int m=messageReceived.indexOf((String)(v.elementAt(z)));
                // /* the message sent to the receiver will be the <sender's name> + message */
                outputToClient.println("<"+client_name+">"+messageReceived.substring(m));
            @Override
           synchronized public void run() {
                try {
                     inputFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                     outputToClient = new PrintWriter(socket.getOutputStream(),true);
                     client_name = inputFromClient.readLine();
                     v.addElement(client_name);
                     outputToClient.println("Welcome, "+client_name+"the current users on the chat are :");
                     for(int j =0;j<v.size();j++)
                         if(v.isEmpty())
                             outputToClient.println("none,you are the initiator! Go on.... ");
                         else
                         outputToClient.println(v.elementAt(j));
                     outputToClient.println("To message to all write : 'MSG' followed by your message");
                     outputToClient.println("To private message: 'username' 'your mesage' ");
                    while (true) {
                        messageReceived = inputFromClient.readLine();
                        if(messageReceived.startsWith("MSG"))
                        for(int i=0;i<v.size();i++)
                              // v.elementAt(i).toString();
                            ((MultiThreadedServer3)(v.elementAt(i))).send();
                        for(z=0;z<v.size();z++)
                            if(messageReceived.startsWith((String)(v.elementAt(z))));
                            ((MultiThreadedServer3)(v.elementAt(z))).send_personal();
                           } // close while
                } //close try
                catch (IOException ex)
                    System.err.println(ex);
           } // close run
        public static void main(String[] args) {
            new MultiThreadedServer3();
    } // close MultiThreadServer

    my client code is as follows:
    CLIENT:
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    public class SimpleClient extends JFrame implements ActionListener {
        private JTextField jtfMessageToSend = new JTextField();
        private JTextArea jtaMessageReceived = new JTextArea();
        private JButton btnSend = new JButton("Send");
        private PrintWriter toServer;
        private BufferedReader fromServer;
        /** Creates a new instance of SimpleClient */
        public SimpleClient() {
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            p.add(new JLabel("Message to send: "), BorderLayout.WEST);
            btnSend.addActionListener(this);
            btnSend.setMnemonic('s');
            //btnSend.setActionCommand("active");
            p.add(btnSend, BorderLayout.EAST);
            p.add(jtfMessageToSend, BorderLayout.CENTER);
            jtfMessageToSend.setHorizontalAlignment(JTextField.LEFT);
            jtaMessageReceived.setEditable(false);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(p, BorderLayout.SOUTH);
            getContentPane().add(new JScrollPane(jtaMessageReceived), BorderLayout.CENTER);
            jtfMessageToSend.addActionListener(this);
            setTitle("SimpleClient");
            setSize(500, 300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            try {
                Socket socket = new Socket("localhost", 4242);
                fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                toServer = new PrintWriter(socket.getOutputStream(),true);
            catch (IOException ex) {
                jtaMessageReceived.append(ex.toString());
        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            if (e.getSource() instanceof JTextField || e.getSource() == btnSend) {
                toServer.println(jtfMessageToSend.getText());
                    toServer.flush();
                    jtfMessageToSend.setText("");
                while(!(jtfMessageToSend.getText()).equals("bye"))
                try
                    String messageToDisplay = fromServer.readLine();
                    jtaMessageReceived.append(messageToDisplay + "\n");
                    toServer.println(jtfMessageToSend.getText());
                    //toServer.flush();
                    jtfMessageToSend.setText("");
                catch (IOException ex) {
                    System.out.println("Error in cummunication" +ex);
        public static void main(String[] args) {
            new SimpleClient();
    }

  • Help! how to refresh the JTable of a class from another thread class

    there is an application, in server side ,there are two classes, one is a class called face class that screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much

    thank you very much !
    i tried it ,but the TableModel i used like this ,and how to change the TableModel?
    here the files of mine ,pls give me some help,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write?? }
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

  • Is it possible to create Thread for Swing Components or for JApplet?

    Can i create a Thread by extending Thread class or implementing Runnable interface for Swing Components?
    Can i create a Thread by extending Thread class or implementing Runnable interface with JApplet?
    thanks

    Does your website live on a Windows server? The above link you posted will require a Windows server for that to work but if you do, then you should be able to just follow the links instructions.
    If your site is not on a Windows server (maybe it's on Linux?) then you would most likely need a PHP solution - something like this: http://www.w3schools.com/php/php_mail.asp. Depending on your host, they might actually have a ready-built form script for you to use so it might be best to ask them first.
    You might also want some kind of validation to ensure you receive the correct information so something like jQuery Validate could work.

  • Why are there 2 ways to create threads?

    Hi,
    To create threads, there are two methods
    1) Inherit the THREAD super-class
    2) Implement the interface RUNNABLE.
    The reason for providing two methods is that, the user can only one level of "implementation inheritance". That is the reason, which comes immediately to mind. But is there another reason(s)? If yes, than what is the reason??
    Any help would be welcome
    Thanks in advance

    I think that the main reason is that java does not support multiple inheritance. If you need to have a thread functionality and facilities from another class except Thread simultaneously you can do it implementing Runnable and extending other class in your class.

  • Where is better to create Thread?

    I know there are two way to create thread, one is in subclass of MIDlet for itself
    public class BaseDevice extends MIDlet implements Runnable {
    private Thread thread;
    protected void startApp() {
         if (thread == null) {
              thread = new Thread(this);
              thread.start();
    another is in subclass of Canvas or GameCanvas, I want to know which one is better.
    public class BaseDevice extends MIDlet {
         public static BaseCanvas canvas;
         public NumberPlace() {
              canvas = new BaseCanvas(this);
              Display.getDisplay(this).setCurrent(canvas);
              (new Thread(canvas)).start();          
    }

    hi, why do we need thread? either you are doing some n/w related task or animation.
    so better make thread in that class where you are doing such task. so in this case make in subclass.

  • Creating Threads : New thread doesn't run( )

    Hello !
    Can anyone please check the error in this code. It does not start the new thread.
    God bless you.
    NADEEM.
    // Create a second thread
    class NewThread implements Runnable {
      Thread t ;
      NewThread() {
      try {
       t = new Thread(this.t , "New Thread");           // Create a new, second thread.
       System.out.println("Child Thread : " + t);
       t.start();                                        // start the thread.
       }catch (IllegalThreadStateException e) {
         System.out.println("Exception : " + e);
      //Entry point for the second thread.
      public void run() {
       try {
        for(int i = 5; i > 0; i--) {
        System.out.println("Child Thread  : " + i);
        Thread.sleep(500);
       }catch (InterruptedException e) {
         System.out.println("Child Thread interrupted ");
       System.out.println("Exiting Child Thread... ");
    class CreatingThread {
    public static void main(String args[]) {
       new NewThread();    // Create a new Thread
       try {
        for(int i = 5; i > 0; i--) {
         System.out.println("Main Thread : " + i);
         Thread.sleep(1000);
       } catch (InterruptedException e) {
         System.out.println("Main Thread interrupted ");
       System.out.println("Exiting main thread ");

    are you sure Nadeem...i compiled and ran the below code and it works as you designed it...what errors do u get when u try to compile?...
    class NewThread implements Runnable {
      Thread t ;
      NewThread() {
      try {
       t = new Thread(this , "New Thread");           // Create a new, second thread.
       System.out.println("Child Thread : " + t);
       t.start();                                        // start the thread.
       }catch (IllegalThreadStateException e) {
         System.out.println("Exception : " + e);
      //Entry point for the second thread.
      public void run() {
       try {
        for(int i = 5; i > 0; i--) {
        System.out.println("Child Thread  : " + i);
        Thread.sleep(500);
       }catch (InterruptedException e) {
         System.out.println("Child Thread interrupted ");
       System.out.println("Exiting Child Thread... ");
    class CreatingThread {
    public static void main(String args[]) {
       new NewThread();    // Create a new Thread
       try {
        for(int i = 5; i > 0; i--) {
         System.out.println("Main Thread : " + i);
         Thread.sleep(1000);
       } catch (InterruptedException e) {
         System.out.println("Main Thread interrupted ");
       System.out.println("Exiting main thread ");
    }

Maybe you are looking for

  • WVC54GCA no longer working on wireless

    I had the camera for about 2 months and it was working fine wirelessly. The only problem I had was the camera randomly disconnects and gets reassigned a new IP so I set it to static and it worked fine. About 2 weeks ago it stopped working. I connecte

  • Testing through RWB under Adapter Engine

    Hi All I know i can test my scenario through RWB through Test tab. The problem i am facing is---- when i am testing using Integration Engine after providing necessary details i am getting a message in moni thats fine but when i am testing the same sc

  • R/3 upgradation & impact on BI

    Hi , i am in SAP BI  (7.0) ,now my R/3 system is upgrading from 4.6 to 6.0, not BI.What would be the necessary settings required from BI perspective? like data loads ,queries,web templates what are the necessary steps we shuld take? please explain me

  • When do i use Apple Id and when do I when do i use icloud?

    When I am asked for APPLE ID, I use that name and password. Is there anytime I should be using my icould instead. What circumstances would call for using icloud?

  • Workbench Request not accepted by SAP NW

    I work on SAP NetWeaver 7.0. The system prompt for Workbench request. I entered CTS. But the system did not accept it. The system told me the value not exist. I also tried other valus: RSMON, SPRO. The system still does not like the values. What valu