美文网首页
Thread和Runnable的区别

Thread和Runnable的区别

作者: zheng7 | 来源:发表于2018-04-18 04:56 被阅读0次
    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和Runnable的区别

          本文链接:https://www.haomeiwen.com/subject/ltvmkftx.html