Java中Runnable和Thread的区别

package cn.timebusker.concurrent;

/**
 * 讨论 Thread And Runnable 的区别
 */
public class ThreadAndRunnable {

    // 1. 通过继承Thread类,重写Thread的run()方法,将线程运行的逻辑放在其中
    // 2. 通过实现Runnable接口,实例化Thread类
    // 两种方式最终都是通过调用start()方法来实现多线程。切记不能直接调用Thread类或Runnable对象的run()方法,因为直接调用run()方法,
    // 只会执行同一个线程中的任务,而不会启动新线程。调用start()方法将会创建一个执行run()方法的线程。

    private int ticket = 10;

    private String name;

    public ThreadAndRunnable(String name) {
        this.name = name;
    }

    public void runnabletest() {
        // 类似于通过继承Thread类,同时重写run()方法
        Runnable runnable = new Runnable() {
            public void run() {
                for (int i = 0; i < 500; i++) {
                    if (ticket > 0) {
                        System.out.println(name + "卖票---->" + (--ticket));
                    }
                }
            }
        };
        new Thread(runnable).start();
    }

    public void threadtest() throws Exception {
        // 类似于实现Runnable类接口的run()方法,再结合Thread类来实现多线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 500; i++) {
                    if (ticket > 0) {
                        System.out.println(name + "卖票---->" + (--ticket));
                    }
                }
            }
        });
        thread.start();
    }

    public static void main(String[] args) throws Exception {
        /**
         * 网上多篇博客说明 通过实现 Runnable接口可以方便的完成线程之间的资源共享。理由多如: Runnable r = new
         * MyRunnable(); ==》 Thread t1 = new Thread(r, "线程a");
         * 多线程的实现形式多样,如本案例的中的两个案列。
         * 
         * 就起根源:Thread类本身就是实现了Runnable接口==》最终实现的public void run()方法创建线程时,
         * 均需要交付给Thread类的start()方法执行
         */
        ThreadAndRunnable tara = new ThreadAndRunnable("一号窗口");
        ThreadAndRunnable tarb = new ThreadAndRunnable("二号窗口");
        ThreadAndRunnable tarc = new ThreadAndRunnable("三号窗口");

        // tara.runnabletest();
        // tarb.runnabletest();
        // tarc.runnabletest();

        System.out.println("###########################################################");

        tara.threadtest();
        tarb.threadtest();
        tarc.threadtest();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值