Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: Threads - I need some explanations

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Threads - I need some explanations

    Hey,
    Recently I am trying to comprehend the multithreading concept. I was actually able to build a small app for the purpose. A class was GUI, a class was calculating Hailstone sequence and sending the process to the GUI.
    Let me explain what I am failing to understand so that you can at least guide me:
    Think of two classes:
    	public class ClassOne implements Runnable{
     
    		public static void main(String[] args) {
    	    	ClassOne cOne = new ClassOne();
    	    	ClassTwo cTwo = new ClassTwo();
     
    	    	Thread t1 = new Thread(cOne);
    	    	Thread t2 = new Thread(cTwo);
    	    	t1.start();
    	    	t2.start();
    	    	cOne.someMethod();
                    cTwo.angryMethod();
     
    	    }
     
    		@Override
    		public void run() {
    			for(int i=0;i<20;i++){
    			System.out.println("ClassOne run method");
    			try {
    				Thread.sleep(500);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			}
    		}
     
     
    		public void someMethod(){
    			for(int i=0;i<20;i++){
    			System.out.println("ClassOne some method");
    			try {
    				Thread.sleep(500);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			}
    		}
     
    		public void someMethod2(){
    			for(int i=0;i<20;i++){
    			System.out.println("ClassOne some method 2");
    			try {
    				Thread.sleep(500);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			}
    		}
     
    		public void someMethod3(){
    			for(int i=0;i<20;i++){
    			System.out.println("ClassOne some method 3");
    			try {
    				Thread.sleep(500);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			}
    		}
    }

    This is the another one:
    public class ClassTwo implements Runnable{
     
    	@Override
    	public void run() {
    		for(int i=0;i<20;i++){
    		System.out.println("Class Two run method");
    		try {
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		}
    	}
     
    	public void coolMethod(){
    		for(int i=0;i<20;i++){
    		System.out.println("Class Two cool method");
    		try {
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		}
    	}
     
    	public void notSoCoolMethod(){
    		for(int i=0;i<20;i++){
    		System.out.println("Class Two not so cool method");
    		try {
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		}
    	}
     
    	public void angryMethod(){
    		for(int i=0;i<20;i++){
    		System.out.println("Class Two pissed method");
    		try {
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		}
    	}
    }

    So, suppose I created threads to run. A thread executes only what is inside run() methods, right? But I have some other methods here, they will have to be executed, and maybe they will need to communicate.

    Considering we cannot create another method in a method (run method), how do they make it work?
    A thread will come and only read run() method.
    If I call angryMethod() or someMethod2(), this is not multithreading.
    If I call methods from inside of run() methods, all of them will run regardless what I actually wanted.

    So that makes me wonder... Tutorials are simple as expected, they print some stuff to console. I searched for some open source projects and actually downloaded some (One is endlos - a multi-threaded fractal generator for example). I opened every single java file, but I couldn't find Thread or Runnable words
    Another one was too complex for me to understand.

    And I am curious how they implement this?
    Do they make tons of classes for the sake of multithreading? I mean what is this? Please explain or guide me.
    Last edited by beer-in-box; March 6th, 2013 at 09:09 PM. Reason: So the code makes a piece of sense


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    If I call methods from inside of run() methods, all of them will run regardless what I actually wanted.
    If you don't want a method to execute on the run() method's thread don't call it from the run() method. Any method called from the run() method will execute on that thread. Any methods that the called methods call will be executed on that same thread.

    thread executes only what is inside run() method
    That's not true. See above. The run() method is the first method that is called on the new thread.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    I don't understand...
    You are saying that a thread doesn't only run the run() method.

    I edited my previous code to put something to show. They all print their class and method names. I had to surround them with try-catch. So, just examine the main method of class one.

    I did a little test to explain myself:

    I created two threads and called two other methods. Here is my output:
    ClassOne some method
    Class Two run method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne run method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne some method
    ClassOne run method
    Class Two run method
    ClassOne some method
    Class Two run method
    ClassOne run method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne some method
    Class Two run method
    ClassOne run method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne some method
    ClassOne run method
    Class Two run method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne some method
    ClassOne run method
    Class Two run method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne some method
    Class Two run method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne run method
    ClassOne run method
    ClassOne some method
    Class Two run method
    ClassOne run method
    Class Two run method
    ClassOne some method
    ClassOne run method
    ClassOne some method
    Class Two run method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    They seem to work multithread until the run() methods are finished. But they are not. ClassOne some method and Class Two angryMethod (Can see why it's angry ) do not. What I am trying to ask is actually, how do I make that pissed method multithread?

    Another example just came to my mind:
    I have a class to deal with file operations. I have 4 methods plus run() method. These are fileOpen(), fileClose(), fileRead(), fileWrite().
    What I expect to achieve is make these 4 methods run in concurrence with my other classes, say GUI. But with my skills and understanding, I can only make one of these methods run concurrent with other class functions etc. Because I can run fileOpen with multithreading concept only if I call it from run() method.
    But if I do that, then I will never be able to make the other methods in this class multithread.

    Using multithreading I want to achieve this: I run fileOpen, when it is done, then the fileRead will start. But, while these two work, my other class should work as well. This requires multithreading, and I feel like (with my current understanding) I have to sacrifice one of these two methods, because if I start a thread of this class, it will run run() method and then stop.

    Am I clear with my problem now? Honestly, I think I might not be, but I also don't know how to explain further (due to my lack of understanding this concept and maybe my language skills).


    EDIT: OK I might have come up with a proper question: I want both of my methods to be with multithreading capacities. They don't need to run in the same time. When I request fileRead method, it runs as a thread and when I request fileWrite, it runs as a thread with my other possible threads.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    a thread doesn't only run the run() method.
    A thread starts executing the run() method. The run() method can call any other method it wants.
    make these 4 methods run in concurrence
    The OS determines when each thread gets to execute. The code in a thread must do something to tell the OS that it can be interrupted to allow another thread to execute.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    Yes, and I think I did it by Thread.sleep(500). But look at the output. "Class two angry method" did not run until the "Class One some method" stopped.
    So, how do I do that?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    Add some more println statements where the threads are created that print out messages at each step in the execution of the main method that show when when each statement is executed.

    Are you asking about these method calls:
    	    	cOne.someMethod();
                    cTwo.angryMethod();
    The first method must return before the second method will execute.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    That was quick

    Yes, I am asking about these two. I actually don't have any problems with how and when run() methods are called.

    In my mind, when I try to implement multithreading, I think these two should have worked like these;
    	    	t1.start();
    	    	t2.start();
    But they don't.

    I realize I am not running them as a thread, but then again, how do I do that?


    EDIT: I put sysouts like this. And maybe I can explain myself a little better.
    This is my ClassOne main method:
    	public static void main(String[] args) {
    		ClassOne cOne = new ClassOne();
    		ClassTwo cTwo = new ClassTwo();
     
    		Thread t1 = new Thread(cOne);
    		Thread t2 = new Thread(cTwo);
    		System.out.println("t1 will start.");
    		t1.start();
    		System.out.println("t1 started, t2 will.");
    		t2.start();
    		System.out.println("t2 started, someMethod someMethod will.\nAnd no problems so far.");
    		cOne.someMethod();
    		System.out.println("If this is a multithread app, then cTwo should start before someMethod finishes" +
    				"\nActually I would think that angryMethod would start when someMethod() is sleeping" +
    				"\nI put Thread.sleep(500) for this purpose. But it does not.");
    		cTwo.angryMethod();
     
     
    	}

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    they don't.
    Please explain what doesn't happen.
    Add the value returned by the System class's currentTimeMillis() method to all printed messages so you see when they were executed.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    OK, here is my output (I put currentMillis thing to outside of the for loops).
    t1 will start. 1362667052439
    t1 started, t2 will. 1362667052439
    t2 started, someMethod someMethod will.
    And no problems so far.  1362667052439
    1362667052439
    1362667052439
    Class Two run method
    ClassOne run method 1362667052439
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667052940
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667053440
    ClassOne some method
    ClassOne run method 1362667053941
    Class Two run method
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667054441
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667054942
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667055442
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667055943
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667056443
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667056944
    ClassOne some method
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667057444
    ClassOne run method 1362667057944
    Class Two run method
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667058445
    ClassOne some method
    ClassOne run method 1362667058945
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667059446
    Class Two run method
    ClassOne some method
    ClassOne run method 1362667059946
    Class Two run method
    ClassOne some method
    ClassOne run method 1362667060447
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667060947
    ClassOne some method
    Class Two run method
    ClassOne run method 1362667061448
    Class Two run method
    ClassOne some method
    ClassOne run method 1362667061948
    ClassOne some method
    Class Two run method
    If this is a multithread app, then cTwo should start before someMethod finishes
    Actually I would think that angryMethod would start when someMethod() is sleepingI put Thread.sleep(500) for this purpose. But it does not.
    1362667062449
    1362667062449
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method
    Class Two pissed method

    This is what happening.
    But what I think should happen is Class Two angry method (Should've given nicer names) should start before ClassOne someMethod finishes.

    Look at run() methods and someMethod in my output. Because two run methods are multithreading, someMethod could find a way to start executing before the other two run methods finish.

    The same case should have been for angryMethod too. But because someMethod takes all the time, angryMethod cannot start.

    I have Thread.sleep() in someMethod. So, if someMethod and angryMethod were multithreading, angryMethod could start one of the times when someMethod was sleeping.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    angry method (Should've given nicer names) should start before ClassOne someMethod finishes.
    That was explained in post#6. first method must finish before second method can start.
    The two methods are executing on the same thread.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    And that is where my real struggle starts. How do I make these two run from different threads?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    Put the calls to the methods inside separate run() methods and create and start threads as is done in post#1
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    I asked the question wrong. So you gave me an answer which is obvious to me. Here is my problem:

    I have one run() method per one class. But I have three other methods in every class.
    I need this: When I want to call someMethod from the ClassOne and angryMethod from the ClassTwo, they should run multithread. This, I can do.
    But if I call these from run() methods, I have no means of calling someOtherMethod from ClassOne and coolMethod from ClassTwo. Because my run() methods are calling angryMethod and someMethod.

    Let's assume this is ClassOne run() method:
    public void run(){
    //some other stuff if I wanted to
    someMethod();
    }
    And this is ClassTwo run() method:
    public void run(){
    //some other stuff if I wanted to
    angryMethod();
    }
    Now I call someMethod and angryMethod from different threads. I understand this. But I also want coolMethod and someOtherMethod to be multithreading.
    Now, if I put these into run() methods, then either I should remove someMethod and angryMethod, or I will let them run together. But this is not what I want.
    So, it becomes this:
    public void run(){
    //some other stuff if I wanted to
    someMethod();
    someOtherMethod();
    }
    And this is ClassTwo run() method:
    public void run(){
    //some other stuff if I wanted to
    angryMethod();
    coolMethod();
    }
    Here, I have no means to run coolMethod without running angryMethod. But I want it to be multithreading. If I remove angryMethod, then I can't run it multithread, if I remove coolMethod, then I can't run it multithread.

    This is my real problem. Is this achieved by some technique I am not aware of? Or is it not possible? And if it is not possible, how is this being a 'multithreading'?

    With my current knowledge, if I want to run these four methods from different threads, I have to have four classes. And this would wipe the class and method technique away, because I would have one method per one class.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    But I want it to be multithreading.
    Create a new thread with its run() method that calls the methods that you want to execute on that thread.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    beer-in-box (March 7th, 2013)

  16. #15
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    Like this? Look how I created t3 thread please.
    I had to make them static, because I run them in the main method which is static.

    public class ClassOne implements Runnable {
    	static ClassOne cOne = new ClassOne();
    	static ClassTwo cTwo = new ClassTwo();
    	static Thread t1 = new Thread(cOne);
    	static Thread t2 = new Thread(cTwo);
     
     
    	static Thread t3 = new Thread(new Runnable(){
    		@Override
    		public void run() {
    			System.out.println("Thread 3 is starting... "+ System.currentTimeMillis());
    			cTwo.angryMethod();
    		}			
    	});
     
     
     
    	public static void main(String[] args) {
     
    		System.out.println("t1 will start. "+System.currentTimeMillis());
    		t1.start();
    		System.out.println("t1 started, t2 will. "+System.currentTimeMillis());
    		t2.start();
    		System.out.println("t3 is about to start");
    		t3.start();
     
    	}

    Is this the normal (usual or widespread) way of doing this?
    Last edited by beer-in-box; March 7th, 2013 at 10:04 AM. Reason: No bold text in CODE labels :)

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    Is this the normal (usual or widespread) way of doing this?
    No. Usually nothing is static except for the main() method.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    I meant the starting thread.
    Do the real world applications start the thread as I started? I mean like;
    private Thread t3 = new Thread(new Runnable(){
    		@Override
    		public void run() {
    			System.out.println("Thread 3 is starting... "+ System.currentTimeMillis());
    			cTwo.angryMethod();
    		}			
    	});
     
    	private Thread t2 = new Thread (new Runnable(){
    		public void run(){
                            System.out.println("My new t2 thread is this. Starting: " + System.currentTimeMillis());
    			cTwo.coolMethod();
    		}
    	});

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Threads - I need some explanations

    Not sure what the "real world" is. Here is some code I've used to start some threads:
     
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                MyServer.main(args);
             }
          });
          t1.start();
     
          try{Thread.sleep(100);}catch(Exception x){}
     
          Thread t2 = new Thread(new Runnable() {
             public void run() {
                MyClient.main(args);
             }
          });
          t2.start();
    If you don't understand my answer, don't ignore it, ask a question.

  20. The Following User Says Thank You to Norm For This Useful Post:

    beer-in-box (March 7th, 2013)

  21. #19
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Threads - I need some explanations

    lol. Now you said it, I am not sure either I think I meant if this is one of the proper ways of implementing the multithreading concept.

    I see I used the same method as you did with your code snippet.

    Many thanks for your help, also thanks for letting me figure out it and not just typing this in the first place! (No sarcasm, I like it this way)
    I am now tagging the thread as solved.

Similar Threads

  1. Redirections for many threads
    By Norm in forum Forum Updates & Feedback
    Replies: 17
    Last Post: January 5th, 2012, 06:27 AM
  2. Use of threads in an animation
    By 2by4 in forum Java Theory & Questions
    Replies: 5
    Last Post: December 15th, 2011, 08:47 AM
  3. Problem with threads
    By Shahram in forum Threads
    Replies: 4
    Last Post: October 14th, 2011, 06:43 AM
  4. threads
    By crazed8s in forum Threads
    Replies: 2
    Last Post: December 14th, 2010, 04:33 AM
  5. [SOLVED] Fixing of bug for a small program
    By Koren3 in forum Threads
    Replies: 3
    Last Post: April 21st, 2009, 06:28 AM