1

When I do work with Thread.sleep(), I found when current thread invoking sleep() method, other threads could not obtain the processor time to invoke their own. But I get the sleep() method's information from Oracle's doc conversely, so I'm confused.

Here is my code:

class ThreadTest {

    private Runnable mRunnable = () -> {
        println("from runnable start run");
        println("from runnable start end");
    };

    private class TestThread extends Thread {
        @Override
        public void run() {
            super.run();
            println("from Thread start run");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            println("from Thread end");
        }
    }


    private void println(String info) {
        System.out.println(getDate() + " : "+info);
    }

    private String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
        Date date = new Date();// 获取当前时间
        return sdf.format(date);
    }

    void testThread() {
      TestThread thread=  new TestThread();
      thread.run();
        for (int i = 0; i < 10; i++) {
            new Thread(mRunnable).run();
        }
    }
}

and the result is

2018-11-09 18:15:20 PM : from Thread start run

2018-11-09 18:15:23 PM : from Thread end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

Hope someone could help

flakes
  • 21,558
  • 8
  • 41
  • 88
JerryLin
  • 119
  • 1
  • 5

1 Answers1

7

thread.run(); does not start a thread. It just executes the run method in the context of the current thread.

You need to call thread.start()

Similary, you need to call new Thread(mRunnable).start(); to run the runnable in a separate thread.

king_nak
  • 11,313
  • 33
  • 58