Page 1 of 2 12 LastLast
Results 1 to 20 of 25
  1. #1
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Wink [SOLVED] Betterway of writing java Threads

    hi,I am new to java Threads ,so i started to write Threads ,here is my situation [actually this question asked somebody in this forums] .I want to write and then read a file using two threads .Reading Thread starts after writing thread ,here is my code .What i need from u is
    1)Is it a good programm or not
    2)In which areas i need to concetrate for better way writing threads
    3)what are mistakes i had done?
    I want this ,bcs i am trying to learn concepts not copying code.


    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.Scanner;

    /**
    *
    * @author Administrator
    */
    public class ReadWriteThread {
    public static void main(String[] args) {
    try{
    Thread writeThread=new WriteThread();
    Thread readThread=new ReadThread();
    // writeThread.setPriority(1);
    // readThread.setPriority(2);
    writeThread.start();
    readThread.start();
    // System.out.println(writeThread.getPriority());
    // System.out.println(readThread.getPriority());
    }
    catch(Exception e){
    e.printStackTrace();
    }
    }

    }
    class ReadThread extends Thread{
    //ReadThread thread;
    public ReadThread(){
    Thread thread1 =new Thread("ReadThread");
    // thread1.start();
    }
    public synchronized void run(){
    try{
    File f = new File("password1.txt");
    Scanner sc= new Scanner(f);
    ReadFile(sc);
    }catch (Exception e){
    e.printStackTrace();
    }
    }

    private void ReadFile(Scanner sc) {
    System.out.println("Reading File");
    while(sc.hasNext()){
    System.out.println("Data in file " + sc.next());
    }
    }
    }
    class WriteThread extends Thread{
    //ReadThread thread;
    public WriteThread(){
    Thread thread2 =new Thread("WriteThread");
    // thread1.start();
    }
    public synchronized void run(){
    try{
    File f = new File("password1.txt");

    Scanner sc=new Scanner(System.in);
    FileOutputStream fout = new FileOutputStream(f,true);
    System.out.println("Enter Data to Write ,To Stop Data Entry type break");
    String s=sc.next();
    while(!s.equalsIgnoreCase("break")){
    byte[] b=s.getBytes();
    fout.write(b);
    s=sc.next();
    }
    }catch (Exception e){
    e.printStackTrace();
    }
    }
    }

  2. #2
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    This is not a situation where you should use threads. All you want to do is perform two tasks sequentially, so you should write your code like that. Threads are broadly for when you want to do many things at once.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  3. #3
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    ok ,thank u.

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

  5. #5
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    thank u Eranga .
    Last edited by sandeepsai39; 04-20-2009 at 06:00 AM.

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

  7. #7
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    If you do want to know about threading generally, you may also be interested in some stuff I've written on Java thread programming.

    However, I also agree broadly with the poster who commented that it's not clear that what you actually need here is threading. Threading is typically used where your program requires tasks that logically "run at the same time", e.g. handling conversations between several clients on a server, fetching several web pages at once, doing a background search or animation while the user interface is still working etc.

    Having multiple threads can sometimes be useful even when they don't necessarily run at the same time-- just from a "division of labour" point of view to help you design your program. But it's not clear that you have such a complicated case here: you really just want to "do X then do Y", if I understand correctly.

    If you want to practise using threads, think about writing something such as:

    - a program that animates something, while letting the user press a button to start/stop the animation
    - writing a simple server (maybe a chat server, that always seems to be popular) that lets two or more clients connect at the same time
    - if you're mathematically oriented, something that performs a calculation on a multiprocessor machine, and splits the calculation among several threads for speed.

  8. #8
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    ok Eranga .Now Iam reading that artcle only.

  9. #9
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    i know neil ,that is not at all a good program.you suggested some good ones,but my standards are not that level .
    What my problem is in threads after understanding some concepts,to practice threads i am not able to find situtations where to work threds ,not at very high level.I am getting concepts,and i have sufficient time to practice ,but i want some example at my level

  10. #10
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    You can find basis example on Suns' tutorial too. Sorry lol, at the time I don't have a link for this. Search on the site and see.

  11. #11
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    As you said sleep method causes Thrred to sleep for a particular period of time .For example i have two threads say t1 and t2 and i called t1.sleep(10000) bcs of some reasons.In this 10 sec of time i want other thread to do the execution and in 11th sec again t1 should come into picture .How to do this.

  12. #12
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    OK, well, as a simpler example, can you write a program that starts two threads, one which prints "ping" every second, and the other which prints "pong" every 2 seconds?

  13. #13
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    Might I suggest that (just for a peadagogical exercise) you try a classic producer/consumer using two threads. A simple "logging" framework will do for the content. This exercise is informative about how many message queues work.

    If you want to get really funky lets try for multiple producers, and then multiple consumers... Good! now extend that to allow for "dynamic" registration of both produces and consumers; and whalla, you've made your own logging framework.

    -----

    Caveat emptor: Take anything I say seiously at your own risk. Seiously.

  14. #14
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    I write a simple pingpong thread as Neil suggested like below .I want your comments on this .
    If i did any mistakes please tell me ,in which areas i need to improve.
    ok now i start thinking about producer/consumer example

    import java.util.logging.Level;
    import java.util.logging.Logger;


    public class PingPongExample {
    public static void main(String[] args) {
    Thread ping = new Thread(new Ping(),"Ping");
    Thread pong = new Thread(new Pong(),"Pong");
    System.out.println("Time ThreadName");
    ping.start();
    pong.start();
    }
    }
    class Ping implements Runnable{
    int i =0;
    public void run(){
    long starttime =System.currentTimeMillis();
    while(i<20){
    try {
    System.out.println((System.currentTimeMillis()-starttime)/1000 +" "+Thread.currentThread().getName());
    Thread.sleep(1000);
    i++;
    } catch (InterruptedException ex) {
    Logger.getLogger(Ping.class.getName()).log(Level.S EVERE, null, ex);
    }
    }
    }
    }
    class Pong implements Runnable{
    int i = 0;
    public void run(){
    long starttime =System.currentTimeMillis();
    while(i<10){
    try {
    System.out.println((System.currentTimeMillis()-starttime)/1000+" "+Thread.currentThread().getName());
    Thread.sleep(2000);
    i++;
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    }
    }

  15. #15
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Please remember to use code tags. They use this format (code)(/code), however, square brackets are substituted for the brackets... Would just show up as a code box if I did that. I will now study the code...
    Last edited by Singing Boyo; 04-21-2009 at 08:21 AM.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  16. #16
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Ok... getting tired of editing the message. However, code tags are also important because the allow differentiation between classes. They also prevent the posting tool from deleting your tabs. Two quick suggestions... make Ping and Pong nested classes, and make them extend Thread. I'm working on an implementation right now. Also, if you want a more complex example, I have a program that utilizes a similar idea, however, it is more complex. I will post the code or attach it upon request. Also, when I copied the code, your catch block in Ping did not work... may be a local problem for me.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  17. #17
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    ok .Now can any one help me by explaining "happens-before" relationship briefly with simple example .

  18. #18
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    the happens-before relationship is, as far as I know, the idea that one thread may not view the same data as another thread...
    e.g If I have code like the code just below, the printObjects method may be invoked by one thread as the addObject method is invoked by another thread. If this were to happen, the Object added to al by the addObject method would possibly not be printed.
    Java Code:
    private ArrayList<Object> al = new ArrayList<Object>();
    public void addObject(Object o){
         al.add(o);
    }
    public void printObjects(){
         for(int i =0; i<al.size(); i++)
              System.out.println(al.get(i));
    }
    However, code such as the code below would work.
    Java Code:
    /**WARNING:  This code is very poorly written and should NOT, 
    under any circumstances, be used in a program.*/
    
    private ArrayList<Object> al = new ArrayList<Object>();
    
    public synchronized void addOrPrintObjects(Object toAdd, boolean trueToAdd){
         if(trueToAdd = true)
              al.add(toAdd);
         else{
              for(int i =0; i<al.size(); i++)
                   System.out.println(al.get(i));
         }
    }
    As mentioned, the code is very poorly written, as there should be a better way of doing this. However, I can't think of it off the top of my head. If someone can post a better example, please do.

    The basic idea is that a synchronized method ensures that only one thread can call a method at once. By ensuring this, you ensure that any other thread that accesses the method will get the correct information. Again, this is used to some extent in my program.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  19. #19
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default The PingPongExample

    Here is the PingPongExample program with Ping and Pong as nested classes that extend Thread.

    Java Code:
    public class PingPongExample {
    	
    	public PingPongExample(){
    		new Ping().start();//creates and starts the Thread that prints Ping
    		new Pong().start();//creates and starts the Thread that prints Pong
    		System.out.println("Time ThreadName");
    	}
    	
    	public static void main(String[] args) {
    		new PingPongExample();
    	}
    	class Ping extends Thread{
    		int i =0;
    		public void run(){
    			long starttime =System.currentTimeMillis();
    			while(i<20){/** optionally, for(i=0; i<20; i++)
    							may be used to improve readability
    			 			 */
                                    System.out.println((System.currentTimeMillis()-starttime)/1000 +"   Ping");
    				try {
    					sleep(1000);//removed the Thread in Thread.sleep(1000)
    					i++;//if a for loop is used, this can be omitted
    				} catch (InterruptedException ex) {
    					ex.printStackTrace();/** replaced 
    						Logger.getLogger
    						(Ping.class.getName()).log(Level.S EVERE, null, ex);*/
    				}
    			}
    		}
    	}
    	class Pong extends Thread{
    		int i = 0;
    		public void run(){
    			long starttime =System.currentTimeMillis();
    			while(i<10){/** optionally, for(i=0; i<10; i++)
    							may be used to improve readability
    						 */
                                    System.out.println((System.currentTimeMillis()-starttime)/1000+"   Pong");
    				try {
    					sleep(2000);//removed the Thread in Thread.sleep(2000)
    					i++;//if a for loop is used, this can be omitted
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    Last edited by Singing Boyo; 04-21-2009 at 09:10 AM. Reason: Improved code
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  20. #20
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Found a link regarding the happens-before relationship, more specifically synchronization.
    The Java Tutorials: Synchronization
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

Page 1 of 2 12 LastLast

Similar Threads

  1. Java Threads Interview Question
    By _tony in forum Threads and Synchronization
    Replies: 20
    Last Post: 12-22-2008, 08:31 AM
  2. can you give-me a little hand about java threads?
    By masdrobeda in forum New To Java
    Replies: 3
    Last Post: 11-10-2008, 05:15 PM
  3. How to use Java threads
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 06:30 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
  •