×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / 一个简单的JAVA程序:(multi-threading)
    本文发表在 rolia.net 枫下论坛一个有趣的JAVA程序:

    void jButton1_actionPerformed(ActionEvent e)
    {
    Thread test= new Thread(){
    public void run(){
    conn.setUrl("http://localhost:8080/servlet/Servlet1");
    conn.con();}
    };
    test.start();
    }
    void jButton2_actionPerformed(ActionEvent e)
    {
    Thread test= new Thread(){

    public void run(){
    conn.setUrl("http://localhost:8080/servlet/Servlet2");
    conn.con();}
    };
    test.start();
    }


    下面两个METHOD对应GUI上的两个JButton,JButton1按下运行jButton1_actionPerformed,
    JButton2按下运行对应的jButton2_actionPerformed。这两个METHOD的功能是分别通过URLConnection从SERVLET1,SERVLET2
    下载一些简单的HTML CODE并打印在屏幕上。但SERVLET1被有意延时10S。SERVLET2
    没有延时。conn是这个CLASS的成员变量(code 见附)

    问:
    当按下JButton1后马上按下JButton2,会是什么结果
    1)SERVLET1输出的HTML先被打印出来,SERVLET2输出的HTML后被打印出来
    2)SERVLET2输出的HTML先被打印出来,SERVLET1输出的HTML后被打印出来
    3)只有SERVLET1被打印出来
    4)只有SERVLET2被打印出来
    为什么?


    附:conn的code:
    public class Urlconn
    {
    private URL RemoteURL;
    public void setUrl(String url)
    { try{
    RemoteURL=new URL(url);
    }catch (Exception e){}
    }
    public void con()
    {
    try{

    URLConnection AConn =(RemoteURL.openConnection());
    AConn.setDoOutput(true);
    AConn.setDoInput(true);
    AConn.setUseCaches(false);

    BufferedReader in = new BufferedReader(
    new InputStreamReader( AConn.getInputStream()));
    String inputLine;
    StringBuffer buff;
    buff=new StringBuffer();
    while ((inputLine = in.readLine()) != null)
    {
    buff.append(inputLine);
    System.out.println(inputLine);
    }
    in.close();
    }catch (Exception e){}
    }
    }更多精彩文章及讨论,请光临枫下论坛 rolia.net
    • Seems every single enumeration could be correct...
      • I mean all could come true depending on the success and delay of socket connections.
        • CLIENT和SERVER在同一机上。
          • 想想不如找个环境给RUN一下,估计还是那答案;先洗洗睡了,明儿再见。
            • 我已经运行过了,只有一个答案,是2)。不知道为什么。
              • 会不会是因为URLconnection内部机制和JButton这类东西相似也是,EVEN DRIVEN的?
              • Explanation of my thought...
                2) should be the most usually expected result since it occurs when there is no socket connection failures/exceptions; especially when both Client/Server are local, there'd least likely be any issues. 1) appears when connection is slow/delayed; it'll also appear if you switch the setup of delay in the servlets. 3) or 4) occurs when there is a connection failure causing exception.

                This scenario would have been more distinctive if we had connected to remote URL/servlets.
                • In addition, when connecting remotely, there is another possibility of both NOT appearing, isn't there?