Results 1 to 16 of 16
Thread: Java Run Order
- 11-24-2009, 03:47 AM #1
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Java Run Order
I might not be the best java programmer but I thought java waited until the expression ran until it went to the next one, unless you're useing threads.
In my program I run this code:
chatDoc is a Styled Document.Java Code:chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle); System.out.println("---Attemping to Connect...---"); Thread.sleep(1000);
I thought java would first display the text in the Document, then println() and then sleep for 1 sec. However, first it runs println(), then sleeps for a sec, and then displays the text in the Doc. It is very important to my program that the code runs in order. Any ideas for why it doesn't run correctly?
-
Is this a Swing program?
- 11-24-2009, 04:22 AM #3
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Yes, swingworker required?
-
Yes. If you call sleep on a Swing program, you put the EDT to sleep and no component painting (including text updates to text components) gets done. As you've already guessed, use a SwingWorker, and never call Thread.sleep on the EDT.
- 11-24-2009, 04:51 AM #5
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Thanks, but that isnt the real problem, I just used Thread.sleep to find out the orderof output. My real program runs:
clientOS is the client's output stream to a socket. The server is running:Java Code:clientOS.write(username, 0, username.length()); clientOS.newLine(); clientOS.flush();
serverIS = server input streamJava Code:String clientUser; while ((clientUser = serverIS.readLine()) != null) { System.out.println("" + clientUser); System.out.println("" + clientSocket.getInetAddress().getHostAddress()); break; } int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION);
Please note that the server code is running on a seperate Thread.
In my test runs, I an connecting to myself (127.0.0.1) and I want the client to send the server it's username and the server will see this and be asked if they want to accept the connection. In the meantime, the client should see "attempting to connect...". Howver, when I test it, it doesnt display the attemtping to connect, and when the JDialog pops up there is nothing in the middle, just the frame, and then the program hangs. If you need I can post more code.
-
It still smells like a threading issue. Yeah, please post more code if you can.
- 11-24-2009, 05:14 AM #7
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Note: thread waitForConnection is run in main(), and connect() is run from the Swing actionPreformed() with the hostIP as 127.0.0.1 (local)Java Code:Thread waitForConnection = new Thread() { public void run() { try { echoServer = new ServerSocket(7890); clientSocket = echoServer.accept(); handleClient(); } catch (IOException e) { handleException(e); waitForConnection.run(); } } }; public void handleClient() { try { serverIS = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); serverOS = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String clientUser; while ((clientUser = serverIS.readLine()) != null) { System.out.println("" + clientUser); System.out.println("" + clientSocket.getInetAddress().getHostAddress()); break; } int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION); if (accept == 1){ connected = false; serverOS.write("no", 0, 2); serverOS.newLine(); serverOS.flush(); serverIS.close(); serverOS.close(); clientSocket.close(); return; } serverOS.write("yes", 0, 3); serverOS.newLine(); serverOS.flush(); while((input = serverIS.readLine()) != null) { chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle); scrollPaneToBottom(); } } catch (Exception e) { handleException(e); } } public void connect() { connected = false; int i=0; String check; try { hostname = JOptionPane.showInputDialog(null, "Connect to Host IP Adress as " + username + " :"); chatSocket = new Socket(hostname, 7890); clientIS = new BufferedReader(new InputStreamReader(chatSocket.getInputStream())); clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket.getOutputStream())); chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle); System.out.println("---Attemping to Connect...---"); clientOS.write(username, 0, username.length()); clientOS.newLine(); clientOS.flush(); while(((check = clientIS.readLine()) != null) && !connected) { if (check == "yes") { connected = true; chatDoc.insertString(chatDoc.getLength(), "---Sucessfully Connected to " + hostname + "---\n", alertStyle); } else { chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + "---\n", alertStyle); } if ( i == 5000) { chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + ", Server would not respond(timeout)---\n", alertStyle); break; } i++; } while((input = serverIS.readLine()) != null) { chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle); scrollPaneToBottom(); } } catch (Exception e) { handleException(e); } }Last edited by collin389; 11-24-2009 at 05:39 AM.
-
Meaning that connect() will be run on the EDT including Thread.sleep.connect() is run from the Swing actionPreformed()
And this code:
suggests that you're trying to manipulate Swing directly from within a background thread.Java Code:while((input = serverIS.readLine()) != null) { chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle); scrollPaneToBottom(); }
Yeah you have some serious thread issues I believe. Also, you may want to fix these boys:
If you need more help, you may wish to learn about, create and post a Short, Self Contained, Correct (Compilable), Example or SSCCE for short. The link will show you how to do this. You will need to substitute all your connections and whatnots with Thread.sleep to emulate server-client connections or anything else that takes a bit of time to perform.Java Code:if (check == "yes")
Last edited by Fubarable; 11-24-2009 at 05:36 AM.
- 11-24-2009, 05:38 AM #9
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Sorry, the Thread.sleep() shouldn't have been there, and whats wrong with if (check == "yes")
- 11-24-2009, 05:43 AM #10
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
I think I know why, Because, when I call JDialog(), it uses EDT which is being used by connect, even though it is being called from it's own thread. Is there any way I could call connect() from the main Thread, or will i have to make a new one? Also, I still don't know why it wont display the text in chatDoc. Shouldn't it wait until the text is Displayed before it goes to the next line?
-
Doesn't matter. All that connection stuff will likely put your app to sleep and should probably be done from within a SwingWorker. You can update the text fields via publish / process.
When you use == you are checking to see if two variables refer to the same object, but that's not what you want to know here. You want to know if the two String objects hold the same character sequence. That's why you always compare Strings with the equals(...) or equalsIgnoreCase(...) methods.and whats wrong with if (check == "yes")Last edited by Fubarable; 11-24-2009 at 06:13 AM.
-
I have no idea. You'll need to create an SSCCE for us to use your code and see what works and what doesn't.
Last edited by Fubarable; 11-24-2009 at 06:14 AM.
- 11-24-2009, 06:15 AM #13
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
Its still pretty big, but it runs:
-you have to connect to 127.0.0.1Java Code:import java.awt.*; import java.util.*; import javax.swing.*; import javax.swing.text.*; import java.awt.event.*; import java.io.*; import java.lang.*; import java.net.*; public class CMessage extends JFrame implements ActionListener { String username = "Username"; JMenuBar menuBar; JMenu fileMenu; JMenuItem itmConnect; JMenuItem itmDisConnect; JMenuItem itmQuit; JTextPane chatText; StyledDocument chatDoc; JScrollPane chatScroll; JTextField inputText; JScrollPane inputScroll; Style userStyle, clientStyle, alertStyle; boolean connected = false; String line; BufferedReader serverIS = null; BufferedWriter serverOS = null; BufferedReader clientIS = null; BufferedWriter clientOS = null; Socket clientSocket = null, chatSocket = null; ServerSocket echoServer = null; String input; String hostname; public CMessage() { //Menubar and menus menuBar = new JMenuBar(); //File menu fileMenu = new JMenu("File"); menuBar.add(fileMenu); //Connect Button itmConnect = new JMenuItem("Connect", KeyEvent.VK_C); fileMenu.add(itmConnect); itmConnect.addActionListener(this); //Disconnect Button itmDisConnect = new JMenuItem("Disconnect", KeyEvent.VK_D); fileMenu.add(itmDisConnect); itmDisConnect.addActionListener(this); //Separator fileMenu.addSeparator(); //Quit Button itmQuit = new JMenuItem("Quit", KeyEvent.VK_Q); fileMenu.add(itmQuit); itmQuit.addActionListener(this); //End Buttons //End Menus //End Menubar //Add Chat Textarea chatText = new JTextPane(); chatText.setEditable(false); chatText.setAutoscrolls(true); chatDoc = chatText.getStyledDocument(); userStyle = chatText.addStyle("User", null); StyleConstants.setForeground(userStyle, Color.red); clientStyle = chatText.addStyle("Client", null); StyleConstants.setForeground(clientStyle, Color.blue); alertStyle = chatText.addStyle("Alert", null); StyleConstants.setForeground(alertStyle, Color.black); StyleConstants.setAlignment(alertStyle, StyleConstants.ALIGN_CENTER); //Add Chat Textarea ScrollPane chatScroll = new JScrollPane(chatText); //Add all JFrame setLayout(new BorderLayout()); setJMenuBar(menuBar); add(chatScroll, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String event = e.getActionCommand(); if (event == "Connect") { connect(); } if (event == "Disconnect") { disconnect(); } if (event == "Quit") { disconnect(); System.exit(0);} } Thread waitForConnection = new Thread() { public void run() { try { echoServer = new ServerSocket(7890); clientSocket = echoServer.accept(); handleClient(); } catch (IOException e) { handleException(e); waitForConnection.run(); } } }; public void handleClient() { //connected = true; try { serverIS = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); serverOS = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String clientUser; while ((clientUser = serverIS.readLine()) != null) { System.out.println("" + clientUser); System.out.println("" + clientSocket.getInetAddress().getHostAddress()); break; } int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION); if (accept == 1){ connected = false; serverOS.write("no", 0, 2); serverOS.newLine(); serverOS.flush(); serverIS.close(); serverOS.close(); clientSocket.close(); return; } serverOS.write("yes", 0, 3); serverOS.newLine(); serverOS.flush(); while((input = serverIS.readLine()) != null) { chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle); } } catch (Exception e) { handleException(e); } } public void connect() { connected = false; int i=0; String check; try { hostname = JOptionPane.showInputDialog(null, "Connect to Host IP Adress as " + username + " :"); chatSocket = new Socket(hostname, 7890); clientIS = new BufferedReader(new InputStreamReader(chatSocket.getInputStream())); clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket.getOutputStream())); chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle); System.out.println("---Attemping to Connect...---"); clientOS.write(username, 0, username.length()); clientOS.newLine(); clientOS.flush(); while(((check = clientIS.readLine()) != null) && !connected) { if (check == "yes") { connected = true; chatDoc.insertString(chatDoc.getLength(), "---Sucessfully Connected to " + hostname + "---\n", alertStyle); } else { chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + "---\n", alertStyle); } if ( i == 5000) { chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + ", Server would not respond(timeout)---\n", alertStyle); break; } i++; } while((input = serverIS.readLine()) != null) { chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle); } } catch (Exception e) { handleException(e); } } public void disconnect() { if (!connected) { return; } try { if (echoServer != null) { echoServer.close(); } if (chatSocket != null) { chatSocket.close(); } if (clientSocket != null) { clientSocket.close(); } if (serverIS != null) { serverIS.close(); } if (serverOS != null) { serverOS.close(); } if (clientIS != null) { clientIS.close(); } if (clientOS != null) { clientOS.close(); } } catch (Exception e) { handleException(e); disconnect(); waitForConnection.run();} connected = false; } public void handleException(Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } public static void main( String args[] ) { final CMessage window = new CMessage(); window.setSize( 300, 400 ); window.setTitle("Collin's Instant Messager"); window.setVisible( true ); window.setLocation( (0 ), (0)); window.setResizable(true); window.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); window.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent we) { window.disconnect(); System.exit(0); } }); window.disconnect(); window.waitForConnection.run(); } }
-
I don't do client server apps, so I don't know if that portion is correct, but if I place stuff into a SwingWorker, it works better. for instance
Java Code:public void connect() { connected = false; hostname = JOptionPane.showInputDialog(null, "Connect to Host IP Adress as " + username + " :"); //!! added if (hostname == null) { return; } SwingWorker<String, String> worker = new SwingWorker<String, String>(){ String check; int i = 0; @Override protected String doInBackground() throws Exception { try { chatSocket = new Socket(hostname, 7890); clientIS = new BufferedReader(new InputStreamReader(chatSocket .getInputStream())); clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket .getOutputStream())); publish("---Attemping to Connect...---\n"); System.out.println("---Attemping to Connect...---"); clientOS.write(username, 0, username.length()); clientOS.newLine(); clientOS.flush(); while (((check = clientIS.readLine()) != null) && !connected) { if (check.equalsIgnoreCase("yes")) { connected = true; publish("---Sucessfully Connected to " + hostname + "---\n"); } else { publish("---Failed to Connect to " + hostname + "---\n"); } if (i == 5000) { publish("---Failed to Connect to " + hostname + ", Server would not respond(timeout)---\n"); break; } i++; } while ((input = serverIS.readLine()) != null) { publish(input + "\n"); } } catch (Exception e) { handleException(e); } return null; } protected void process(List<String> chunks) { for (String chunk : chunks) { try { chatDoc.insertString(chatDoc.getLength(), chunk, alertStyle); } catch (BadLocationException e) { e.printStackTrace(); } } } }; worker.execute(); }
- 11-24-2009, 06:38 AM #15
Senior Member
- Join Date
- Nov 2009
- Posts
- 235
- Rep Power
- 4
String a = "b"
return (a == "b");
that will return true so I don't understand the reason why you have to say
return a.equals("b");
they accomplish the same task.
And thanks for taking the insult off, but I still saw it :)
OK, nevermind. When i tested it i set String one = "one" and said (one == "one") ok, you're right. Thanks very much for all the help.Last edited by collin389; 11-24-2009 at 06:46 AM.
-
Strings are held in a String pool so that Java often will reuse a String object if it can. Thus it is often true that String variable a will == String variable b, but there is no guarantee. For instance, to force the issue, check out this:
Java Code:public class Fu3 { public static void main(String[] args) { String str1 = "Foo"; String str2 = new String("Foo"); System.out.println(str1); System.out.println(str2); System.out.println("str1 == str2: " + (str1 == str2)); System.out.println("str1.equals(str2): " + (str1.equals(str2))); } }Yeah, sorry for that. I spoke in haste and without thought.And thanks for taking the insult off, but I still saw it :)
Similar Threads
-
Instantiation order
By Jeremy720 in forum New To JavaReplies: 3Last Post: 07-17-2009, 03:19 PM -
Sorting in descending order
By santanu in forum New To JavaReplies: 6Last Post: 11-26-2008, 11:43 PM -
Descending order
By santanu in forum New To JavaReplies: 1Last Post: 11-04-2008, 04:33 PM -
Order Management System Java Developer NYC-Core Java/Multi-threading/Socket Developer
By evanp in forum Jobs OfferedReplies: 0Last Post: 07-22-2008, 04:39 PM -
Hibernate order by query thru java solution urgently reqd
By altaf in forum JDBCReplies: 0Last Post: 03-12-2008, 02:23 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks