Thread和Runnable的区别

  1. 实现Runnable接口,可以避免java单继承机制带来的局限;
  2. 实现Runnable接口,可以实现多个线程共享同一段代码(数据);
    ex:

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();
        thread1.start();
        thread2.start();
        thread3.start();
        
        MyRunnable runnable1 = new MyRunnable("r1");
        
        new Thread(runnable1).run();
        new Thread(runnable1).run();
        new Thread(runnable1).run();
        
    }

}

class MyThread extends Thread
{
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
            System.out.println(currentThread().getName() + " things:" + things);
            things--;
        }
    }
}

class MyRunnable implements Runnable
{
    String name;
    
    public MyRunnable(String name)
    {
        this.name = name;
    }
    
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
            things--;
            System.out.println(name + " things:" + things);
        }
        
    }
}


运行结果:

Thread-2 things:5
r1 things:4
r1 things:3
Thread-1 things:5
Thread-1 things:4
Thread-1 things:3
r1 things:2
Thread-2 things:4
Thread-2 things:3
Thread-2 things:2
Thread-2 things:1
r1 things:1
Thread-1 things:2
r1 things:0
Thread-1 things:1
Thread-0 things:5
Thread-0 things:4
Thread-0 things:3
Thread-0 things:2
Thread-0 things:1

注解:多个Thread可以同时加载一个Runnable,当各自Thread获得CPU时间片的时候开始运行runnable,runnable里面的资源是被共享的。

  1. 线程池只能放入实现Runable或Callable类线程,不能直接放入继承Thread的类。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 线程Thread的5状态:创建——>就绪——>运行——>阻塞——>停止创建:new就绪:创建对象后,执行start...
    ShereenAo阅读 1,167评论 0 5
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,839评论 18 399
  • 因为长期便秘,前阵子朋友介绍在一家信佛的网店买水果酵素喝,调理肠胃。 半个月了,多年便秘才只是稍有改善,但意外发现...
    止末阅读 2,629评论 0 3
  • 语文老师结束表演的时候刚好下了课,我把作业还给林安,顺便把纸条还了回去,我还在上面写了一个问题 “你为什么要向我道...
    柚子寒一阅读 274评论 0 0
  • 还有没有比人类更喧嚣的物种, 不是因为饥饿而觅食, 不在安静里找寻影子, 没有奢望小楷写就的故事, 从乐园里发现的...
    百字生阅读 418评论 0 6