×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT杂谈 / Toy code for Java Thread
    This morning, I discussed Thread with a friend. We cooked up some toy code. I postit here for reference in the future discussion




    class MyThread extends Thread
    {

    public void run()
    {
    int x=0;
    while(x<10)
    {
    System.out.println("x=" +x);
    try{
    Thread.sleep(1000);
    } catch (Exception e) {}
    x++;
    }


    }
    } //end of MyThread


    public class Test
    {
    public static void main(String[] args)
    {
    try
    {
    MyThread mt = new MyThread();
    mt.start();
    Thread.sleep(15000);
    System.out.println("I came here");
    if(mt!=null)
    {
    System.out.println("I 'am not null");
    if(!mt.isAlive())
    {
    System.out.println("I am dead!");

    }

    mt.start();
    }
    else
    {
    System.out.println("I 'am null");
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();

    }


    }
    }//end of Test
    • jabber, let me try ...
      Let me try to express my opnion on this program.

      the output is OK when the second Thread.sleep(15000) waits longer time than the first one. If we change 15000 to a number less than 1000, there will have a problem while running. When the while(){} is not over and the System.out.println("I came here") begins, the mt is not null. And System.out.println("I am not null") will be excuted. After this, mt.start() will bring problem because mt has already started. The problem will be catched by system because of try{...}catch{...}. Then the e.printStackTrace() will be executed. The rest output of System.out.println("x = "+ x); is OK.
      • Happy to see your explanation...
        I cooked up this example as I tried to help one of my colleagues to debug his code.
        Most of us know that a Thread cannot be started more than one time....But my friend did make such a mistake in his code: try to restart a thread after it have been dead (run() method has been returned).

        No mistake is stupid. But a good programmer should be good at learning lessons from other's mistakes...
      • I think the threshold is not less than 1000.
        First let us ignore the time consumed by executing the code except Thread.sleep().
        Second let us ignore the time deviation caused by the kick of the machine's time clock, other processes running, system management, etc.
        Then the threshold of the sleeping time of the main thread should be 9999 or less, not less than 1000.
        • You are right. I missed one "0".
          • Thank you! Sometimes I mistype "0", "00" and something else too. That always waste my time for debugging.