Results 1 to 11 of 11
Like Tree1Likes
  • 1 Post By Zarah

Thread: Why do "static" methods of Thread class provide information about its instances?

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Why do "static" methods of Thread class provide information about its instances?

    The Thread class contains a number of methods useful for thread management. These include static methods which provide information about (or affect the status of) the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and the thread object.

    1. Static methods show behavior of the class, that is the behavior is common to all instances of the class. It is not exclusive for any single instance of the class.

    "the thread invoking the method" in the above quote is our instance of the Thread class. So how does a static method provide information exclusive to a particular instance of itself?


    2. Is it just by chance that static methods of the Thread class provide information about or affected the status of its instance(s)? Or is it a normal behavior of static methods?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    I haven't looked at the source code for Thread but any object may update a static data structure with information. Then a static method may access that data structure as needed.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Gotcha is offline Member
    Join Date
    Jun 2015
    Location
    America
    Posts
    29
    Rep Power
    0

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    static specifically means instances. Say I want an instance counter it would be static so I could increment it from all instances. Here's a tool I made you can play with.. If it is too hard to understand I will make it a lot easier, let me know. It has document listener across multiple classes, it fires threads across multiple classes.

    Also it was a quickie let me know if it is broken

    MainClass.java
    Java Code:
    public class MainClass implements Runnable {
    	//Counters used for playing with threads 
    	public static int iSrvCounter=0;
    	public static final int iAllowedServers=3;
    
    	/** I am playing with threads. Weaving a cup of Java */
    	protected static Thread[] runningThreads = new Thread[iAllowedServers];
    	protected static Main_GUI[]  serverGUIs = new Main_GUI[iAllowedServers];
    	
    	public void run(){
    	   	 try {
    	   		//Note to self. Do NOT add here: new Thread(new MainClass()
    	 	   	if(iSrvCounter < iAllowedServers){	 
    	 	   /** Open a Main_GUI which in turn opens an associating TCPServer */
    	 	   	serverGUIs[iSrvCounter] = new Main_GUI(Thread.currentThread().toString(), String.valueOf(iSrvCounter));
    	 	   	}
    	   		iSrvCounter++;
    	 	   	Thread.sleep(500);
    	 	  // 	System.out.println("MainClass/Run #ID: " + runningThreads[iSrvCounter].getId());
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	
        public static void main(String[] args) throws InterruptedException {
        		MyProcesses();
        	
    //System.out.println("MainClass/Main method Last Line, Thread ID: "+ runningThreads[iSrvCounter].getId() + "\n\n" + "Still executing:\n"
    //   	 + ".................................................");
       	 	//while(true){Thread.sleep(2000);}
        }
        public static void MyProcesses() throws InterruptedException{
          	do {
            	System.out.println("MyProcesses #" + iSrvCounter + ": " + Thread.currentThread());
            	/** Create a new Thread with Object MyThreads(), name it and call .start */
            	//(new Thread(new MainClass(),"Thread# " +iSrvCounter)).start();
         		/** Create a new Thread and call MainClass.java run */
            	runningThreads[iSrvCounter] = new Thread(new MainClass(), "Server Process: " +iSrvCounter);
            	System.out.println("Threads Active: "+Thread.activeCount());
            	System.out.println("All Stack Traces: " +Thread.getAllStackTraces());
           	 	runningThreads[iSrvCounter].start();
           	 	
    
           	 	/** This is incremented in MyThreads.run */
            	//iCnt++;
            	// NO CODE HERE		/////\\\\\\	 "Unless Increment doesn't matter as it is done in run"
            	Thread.sleep(1100); //<==== <debug> Infinite loop protector sleep 1.1 second on iterations
         	} while (iSrvCounter < iAllowedServers);
    
            }
    }
    Main_GUI.java
    Java Code:
    import java.awt.BorderLayout;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JLabel;
     
    public class Main_GUI {
        /** These are object references being pointed at NEW objects created */
    	
        private JTextArea messagesArea = new JTextArea();
        private JLabel lblStat = new JLabel("Status:");
        private JLabel lblStatMsg = new JLabel("Waiting for connection");
        
        /** Storing the current running thread into a Thread reference */
        private Thread MainGUIThread = Thread.currentThread();
    
        /** This is object references that aren't referencing any objects yet*/
        private MainServer TheServer; //Access to our class.
        private JFrame serFrame;
        
        //Constructor
        public Main_GUI(String sFrameTit, String sID) {
    		serFrame = new JFrame(sFrameTit);
    	    serFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    serFrame.setResizable(false); //JTextArea needs more work
    
    	    Box box = new Box(BoxLayout.LINE_AXIS);
    
    	    box.add(Box.createVerticalGlue());
    	    messagesArea = new JTextArea();
    	    messagesArea.setEditable(true);
    	    messagesArea.setRows(20);
    	    messagesArea.setWrapStyleWord(true);
    	    messagesArea.setLineWrap(true);
    	    box.add(new JScrollPane(messagesArea));
    	    serFrame.getContentPane().add(box, BorderLayout.NORTH);
    	    
    	    box = Box.createHorizontalBox();
    	    JLabel lblStat = new JLabel("Thread: ");
    	    box.add(lblStat);
    	    JLabel lblStatMsg = new JLabel(sID);
    	    box.add(lblStatMsg);
    	    box.add(Box.createHorizontalGlue());
    	    
    	    serFrame.getContentPane().add(box, BorderLayout.SOUTH);
    	    serFrame.setSize(400, 350);
    	    serFrame.setVisible(true);
    	    
            //Start up The Server 
            StartTheTCPServer(); /** MainServer.java is called at this point */
    		
            //Document listener for JTextArea updates us of changes, we send to client.
    		DocumentListener documentListener = new DocumentListener() {
    	        public void changedUpdate(DocumentEvent documentEvent) {
    	          SendIt(documentEvent);
    	        }
    	        public void insertUpdate(DocumentEvent documentEvent) {
    	          SendIt(documentEvent);
    	        }
    	        public void removeUpdate(DocumentEvent documentEvent) {
    	          SendIt(documentEvent);
    	        }
    	        /** SendIT determines the update type in one method and processes it */
    	        private void SendIt(DocumentEvent documentEvent) {
    	          DocumentEvent.EventType type = documentEvent.getType();
    	          //Create a variable and assign the type of change as a string value
    	          String typeString = null;
    	          if (type.equals(DocumentEvent.EventType.CHANGE)) {
    	            typeString = "Change";
    	          }  else if (type.equals(DocumentEvent.EventType.INSERT)) {
    	            typeString = "Insert";
    	          }  else if (type.equals(DocumentEvent.EventType.REMOVE)) {
    	            typeString = "Remove";
    	          }
    	          //Make sure we are live and there were changes (chopped out server checking)
    	          if (typeString != null)
    	          {
    	          
                  // Create a variable and get the text from JTextArea object
    	          String messageText = messagesArea.getText();
                  /** DocumentListener event send through a method in ANOTHER CLASS, separate classes... */
                  TheServer.sendMessage(messageText);
                  //Printing out the current thread
                  System.out.println("Main_GUI/SendIT Thread iD: "+MainGUIThread.getId());
    	          }
    	        }
    	      };
    	      //Add above document listener so if it changes we update the client.
     	      messagesArea.getDocument().addDocumentListener(documentListener);
    
        }
        //Create an instance of the server called from MainServer
        public void StartTheTCPServer() {
            //creates the object OnMessageReceived asked by the MainServer constructor
            TheServer = new MainServer(new MainServer.OnMessageReceived() {
                @Override
                //this method declared in the interface from MainServer class is implemented here
                //this method is actually a callback method, because it will run every time when it will be called from
                //MainServer class (at while)
                public void messageReceived(String message) {
                	String newIP=TheServer.getIp();
                    //<debug> Newline may need to go
                	messagesArea.append("\n "+message);
                	lblStat.setText("Connect:");
                	lblStatMsg.setText(newIP);
                }
            });
            TheServer.start();
        }
    }
    MainServer.java
    Java Code:
    /**
     * The class extends the Thread class so we can receive and send messages at the same time
     */
    public class MainServer extends Thread {
        private boolean running = false;
        private OnMessageReceived messageListener;
        private String ip = "Client is not connected";
        private String message ="";
        private static final int MaxIterate=5000;
        private static int iIterate=0;
    
        /**
         * Constructor of the class
         * @param messageListener listens for the messages
         */
        public MainServer(OnMessageReceived messageListener) {
            this.messageListener = messageListener;
        }
     
        @Override
        public void run() {
            super.run();
     
            ip="127.0.0.1";
            while (running) {
            	iIterate++;
            	if(iIterate > MaxIterate){System.exit(-1);}; //Tired of infinite looping my Intel I7, it's fast...
            	message = "Fake message";
            	//Check if we have an update
                if (message != null && messageListener != null) {
                    //call the method messageReceived from Main_GUI
                    messageListener.messageReceived(message);
                }
                try {
    				Thread.sleep(1000); //Infinite looping blues
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
            }
        }
    
    	//Declare the interface. The method messageReceived(String message) will must be implemented in the Main_GUI
        public interface OnMessageReceived {
            public void messageReceived(String message);
        }
        /**
         * Method to send the messages from server to client
         * @param message the message sent by the server
         */
        public void sendMessage(String message){
        	System.out.println(message);
        	System.out.println("sendMessage|MainServer " +Thread.currentThread());
        	System.out.println("Threads Active: "+Thread.activeCount());
        }
        /** Getter / Setters */
        public String getIp() {
    		return ip;
    	}
    
    	public void setIp(String ip) {
    		this.ip = ip;
    	}
    }
    Last edited by Gotcha; 06-19-2015 at 09:02 AM. Reason: Comments had wrong class names

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    Quote Originally Posted by Gotcha View Post
    static specifically means instances.
    Sure; what planet are you from?

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    In most cases it basically means the exact opposite :/
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    You're example, unfortunately, has too much baggage. I would think something of no more than 20 lines would have sufficed.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Gotcha is offline Member
    Join Date
    Jun 2015
    Location
    America
    Posts
    29
    Rep Power
    0

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    Ok I removed it.. I don't thinkI am very good at helping folks. Honestly I am not good with people.. I think I will leave helping to you gentlemen.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    Quote Originally Posted by Gotcha View Post
    Ok I removed it.. I don't thinkI am very good at helping folks. Honestly I am not good with people.. I think I will leave helping to you gentlemen.
    Never remove a post once it has been responded to. Otherwise, other posts lose context. It will probably be put back.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    Yup, I restored the post.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    Quote Originally Posted by Gotcha View Post
    I don't think I am very good at helping folks.
    Nonsense! Just wait for a while, read some of the replies and get the gist of it. You haven't been a member that long. And I have been "scolded" several times on this forum for making stupid statements. But its never personal.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: Why do "static" methods of Thread class provide information about its instances?

    any object may update a static data structure with information. Then a static method may access that data structure as needed.
    Thank you very much. That clarified it.

    I don't thinkI am very good at helping folks. Honestly I am not good with people..
    You are so wrong. You read a question and took time to answer it, and gave a full-fledged example which is like an application of the concepts I am studying, is enough of an evidence that you are good with people. You also offered help if I find it difficult, which means you are good at helping too. You took time to answer a question - an act which probably isn't of much use to you - I have immense respect for that. I have immense respect for all the people who answer questions here.

    Now about the code you shared, I am very thankful to you for answering my question, and sharing that code sample you wrote. I am just not able to read and understand it yet, because I can only only give a little time to learning Java (and I have like serious reasons for that) each day.

    Honestly, I am myself really confused about if I should just hastily read the surface story and write a short program for practice, or I should take time to let the knowledge really sink in - which means I would probably spend a week for a concept as small as this one, to listen to every question my brain asks, to try to find the answers, and then try to find the answers to the questions which arise from those answers.. and so on.

    But that does not mean I will not look into it. I will definitely study it (and ask you questions) as I am very sure I will learn a lot from this example. I have always faced a problem to materialize how things will apply in real situations. Your tool will give me a chance to understand that kind of thing. And I am more than grateful for your answer. I am sure it will be very useful for me.

    About the long vs a short answer: I can only talk for myself. The first answer (by Jim) is comprised of two sentences, yet it clearly answers the question. I looked at it, got it, and moved on. I looked at your answer, tried to start reading the code, thought that all I know about a server is that it is a computer which serves the data that other computers access remotely, so thought it would take time and I have to rush, so I decided to get back to it in a while. But is my approach of learning a good one? No! I should have read the code, play with it, understood it.... And I am sure many folks who don't have pressures like mine would do exactly that.

    So in a nutshell, both the kinds of answers are helpful for me, in a slightly different way.

    So the conclusion of this jibber-jabber is that I am truly grateful for your answer. It is up to you to decide what kind of answers you want to write in the future, but please, don't be discouraged. =)
    DarrylBurke likes this.

Similar Threads

  1. Replies: 1
    Last Post: 12-04-2013, 09:32 PM
  2. Replies: 1
    Last Post: 11-02-2012, 11:38 PM
  3. Replies: 5
    Last Post: 12-21-2011, 06:44 PM
  4. Replies: 14
    Last Post: 04-08-2011, 06:01 PM
  5. Replies: 1
    Last Post: 11-20-2009, 07:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •