实现runnable接口的类都是任务类,它在run()内部定义任务逻辑。
把任务类对象作为参数创建线程实例,线程就会执行任务。
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
//启动
t.start();
timer是线程,而timertask是任务。
创建一个timer,timer内部会自动创建一个线程。
executors是executor的工厂类。
First thing to understand is that the Thread
class implements Runnable
, so you can use a Thread
instance anywhere you can use Runnable
. For example,
new Thread(new Thread()); // won't do anything, but just to demonstrate
When you create a Thread
with
new Thread(someRunnable);
and start it, the thread calls the given Runnable
instance's run()
method. If that Runnable
instance happens to also be an instance of Thread
, so be it. That doesn't change anything.
When you create a custom thread like
new ExtendsThread();
and start it, it calls run()
on itself.
When you extends Thread class, each of your thread creates unique object and associate with it. where as
When you implement Runnable, it shares the same object to multiple threads..
转载自:stackoverflow Java-Thread Vs Runnable