Home arrow static arrow Java Programming [Archive] - threading problem
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - threading problem
This topic has 11 replies on 1 page.

Posts:26
Registered: 4/29/04
threading problem  
Jul 24, 2004 5:24 AM



 

I am given a new program which is threaded and allow multiople client requests. now what I have to do with this is I have to maintain an array of size 5 and check it each time before a new thread starts because I have to put an entry in that array like '1' means for every incoming requests i have to put a value in that array if any of its fields are empty.
Suppose first request came and I put 1 in arr[0]. second requerst came and put 1 in arr[1]. now when third request came in and thread one done processing then put 1 in arr[0] not in arr[2].
Now where to put that array and how to know if any particular thread ended? Where to use isAlive() function?

Hope I made myself clear

Server Code
import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.*;import javax.swing.*;import java.io.*;import java.net.*; class SocketClient extends JFrame		 implements ActionListener {    JLabel text, clicked;   JButton button;   JPanel panel;   JTextField textField;   Socket socket = null;   PrintWriter out = null;   BufferedReader in = null;    SocketClient(){ //Begin Constructor     text = new JLabel("Text to send over socket:");     textField = new JTextField(20);     button = new JButton("Click Me");     button.addActionListener(this);      panel = new JPanel();     panel.setLayout(new BorderLayout());     panel.setBackground(Color.white);     getContentPane().add(panel);     panel.add("North", text);     panel.add("Center", textField);     panel.add("South", button);   } //End Constructor   public void actionPerformed(ActionEvent event){     Object source = event.getSource();      if(source == button){//Send data over socket          String text = textField.getText();          out.println(text);	  textField.setText(new String(""));//Receive text from server       try{	  String line = in.readLine();          System.out.println("Text received :" + line);       } catch (IOException e){	 System.out.println("Read failed");       	 System.exit(1);       }     }  }   public void listenSocket(){//Create socket connection     try{       socket = new Socket("localhost", 4444);       out = new PrintWriter(socket.getOutputStream(), true);       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));     } catch (UnknownHostException e) {       System.out.println("Unknown host: localhost:127.0.0.1");       System.exit(1);     } catch  (IOException e) {       System.out.println("No I/O");       System.exit(1);     }  }    public static void main(String[] args){        SocketClient frame = new SocketClient();	frame.setTitle("Client Program");        WindowListener l = new WindowAdapter() {                public void windowClosing(WindowEvent e) {                        System.exit(0);                }        };         frame.addWindowListener(l);        frame.pack();        frame.setVisible(true);	frame.listenSocket();  }}


Client Code :-

import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.*;import javax.swing.*; import java.io.*;import java.net.*; class SocketClient extends JFrame		 implements ActionListener {    JLabel text, clicked;   JButton button;   JPanel panel;   JTextField textField;   Socket socket = null;   PrintWriter out = null;   BufferedReader in = null;    SocketClient(){ //Begin Constructor     text = new JLabel("Text to send over socket:");     textField = new JTextField(20);     button = new JButton("Click Me");     button.addActionListener(this);      panel = new JPanel();     panel.setLayout(new BorderLayout());     panel.setBackground(Color.white);     getContentPane().add(panel);     panel.add("North", text);     panel.add("Center", textField);     panel.add("South", button);   } //End Constructor   public void actionPerformed(ActionEvent event){     Object source = event.getSource();      if(source == button){//Send data over socket          String text = textField.getText();          out.println(text);	  textField.setText(new String(""));//Receive text from server       try{	  String line = in.readLine();          System.out.println("Text received :" + line);       } catch (IOException e){	 System.out.println("Read failed");       	 System.exit(1);       }     }  }   public void listenSocket(){//Create socket connection     try{       socket = new Socket("localhost", 4444);       out = new PrintWriter(socket.getOutputStream(), true);       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));     } catch (UnknownHostException e) {       System.out.println("Unknown host: localhost:127.0.0.1");       System.exit(1);     } catch  (IOException e) {       System.out.println("No I/O");       System.exit(1);     }  }    public static void main(String[] args){        SocketClient frame = new SocketClient();	frame.setTitle("Client Program");        WindowListener l = new WindowAdapter() {                public void windowClosing(WindowEvent e) {                        System.exit(0);                }        };         frame.addWindowListener(l);        frame.pack();        frame.setVisible(true);	frame.listenSocket();  }}
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 5:27 AM (reply 1 of 11)



 
Isn't that the same source code posted twice? Isn't the server code the same as the client code?

/Kaj
 

Posts:26
Registered: 4/29/04
Re: threading problem  
Jul 24, 2004 5:34 AM (reply 2 of 11)



 
sorry for that mistake.
here is the serve code
 import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.*;import javax.swing.*; import java.io.*;import java.net.*; class ClientWorker implements Runnable {  private Socket client;  private JTextArea textArea;    ClientWorker(Socket client, JTextArea textArea) {   this.client = client;   this.textArea = textArea;     }   public void run(){    String line;    BufferedReader in = null;    PrintWriter out = null;    try{      in = new BufferedReader(new InputStreamReader(client.getInputStream()));      out = new PrintWriter(client.getOutputStream(), true);    } catch (IOException e) {      System.out.println("in or out failed");      System.exit(-1);    }     while(true){      try{        line = in.readLine();//Send data back to client         out.println(line);         textArea.append(line);       } catch (IOException e) {         System.out.println("Read failed");         System.exit(-1);       }    }  }} class SocketThrdServer extends JFrame{    JLabel label = new JLabel("Text received over socket:");   JPanel panel;   JTextArea textArea = new JTextArea();   ServerSocket server = null;    SocketThrdServer(){ //Begin Constructor     panel = new JPanel();     panel.setLayout(new BorderLayout());     panel.setBackground(Color.white);     getContentPane().add(panel);     panel.add("North", label);     panel.add("Center", textArea);   } //End Constructor   public void listenSocket(){    try{      server = new ServerSocket(4444);     } catch (IOException e) {      System.out.println("Could not listen on port 4444");      System.exit(-1);    }    while(true){      ClientWorker w;      try{        w = new ClientWorker(server.accept(), textArea);        Thread t = new Thread(w);        t.start();      } catch (IOException e) {        System.out.println("Accept failed: 4444");        System.exit(-1);      }    }  }   protected void finalize(){//Objects created in run method are finalized when //program terminates and thread exits     try{        server.close();    } catch (IOException e) {        System.out.println("Could not close socket");        System.exit(-1);    }  }   public static void main(String[] args){        SocketThrdServer frame = new SocketThrdServer();	frame.setTitle("Server Program");        WindowListener l = new WindowAdapter() {                public void windowClosing(WindowEvent e) {                        System.exit(0);                }        };        frame.addWindowListener(l);        frame.pack();        frame.setVisible(true);        frame.listenSocket();  }}
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 5:38 AM (reply 3 of 11)



 
Hi,

Why do you need that array? What are you trying to accomplish?

/Kaj
 

Posts:26
Registered: 4/29/04
Re: threading problem  
Jul 24, 2004 6:11 AM (reply 4 of 11)



 
thats the way my friend wanted it.
so can u plz tell me how to do that?
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 6:22 AM (reply 5 of 11)



 
Just declare the array in SocketThrdServer, and when you are about to create a new thread, loop on the array and see if the elemt is null, or thread.isAlive() == false. In that case just replace that one.

But I don't see why you would like to do this. What should you do if all 5 positions is taken, and all 5 threads are still alive? It would be better to use a thread pool of some kind.

/Kaj
 

Posts:26
Registered: 4/29/04
Re: threading problem  
Jul 24, 2004 6:28 AM (reply 6 of 11)



 
then I will just print a message that stack is full.
 

Posts:26
Registered: 4/29/04
Re: threading problem  
Jul 24, 2004 6:30 AM (reply 7 of 11)



 
how will I identify individual threads ?
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 6:39 AM (reply 8 of 11)



 
You can always use setName, and getName on the thread.

/Kaj
 

Posts:26
Registered: 4/29/04
Re: threading problem  
Jul 24, 2004 7:38 AM (reply 9 of 11)



 
Can U plz tell where to put the setName and array?
I will be greatful if u provide the code for this just the changes.
Something like this :-

class SocketThrdServer extends JFrame {                         String str[]={'a','b','c','d','e'};                           String arr[]= new arr[5];    while(true){     ClientWorker w;       try{              w = new ClientWorker(server.accept(), textArea);              for(int i=0;i<5;i++)   if(arr[I]==0)   {  arr[i]=1;  break;  }              for(int j=0;j<5;j++)   if(arr[j]==1)    System.out.println(" STACK FULL. TRY AGAIN LATER ");                           Thread t = new Thread(w,str[i]);  // creating the thread here                          for(int i=0;i<5;i++)                   if(t.isAlive())                      arr[i]=0;                            t.start(); // starting thread here
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 7:53 AM (reply 10 of 11)



 
Hi,

It would be something like this:

        String[] names = new String[] {"a", "b", "c", "d", "e"};        Thread[] threads = new Thread[5];        while (true) {            ClientWorker w;            try {                w = new ClientWorker(server.accept(), textArea);                //Check threads                int emptyIndex = -1;                for (int i = threads.length-1; i >= 0; i--) {                    if (threads[i] != null && threads[i].isAlive() == false) {                        threads[i] = null;                        emptyIndex = i;                    }                }                if (emptyIndex < 0) {                    System.out.println("Sorry stack full");                    //Here you need to close the socket to the client (worker created)                    continue;                }                threads[emptyIndex] = new Thread(w);                threads[emptyIndex].setName(names[emptyIndex]);                threads[emptyIndex].start();            }            catch (IOException e) {                System.out.println("Accept failed: 4444");                System.exit( -1);            }        }


/Kaj
 

Posts:18,384
Registered: 21.03.00
Re: threading problem  
Jul 24, 2004 7:55 AM (reply 11 of 11)



 
Hi,

I just saw that the if statement should be:

                    if (threads[i] == null || (threads[i] != null && threads[i].isAlive() == false)) {


/Kaj
 
This topic has 11 replies on 1 page.