• 多线程Thread和Runnable的实现


    java中实现多线程有两种方法:一种是继承Thread类,另一种是实现Runnable接口。

    java中只允许单一继承,但允许实现多个接口,因此第二种方法更灵活。

    /**
         * 运行继承java.lang.Thread类定义的线程
         */
        public void startOne() {
            // 创建实例
            OneThread oneThread = new OneThread();
            // 启动线程ThreadA
            oneThread.startThreadA();
            try {
                // 设置线程休眠1秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 停止线程,此处为什么不用stop()方法,因为该方法已经废弃,但可以用在死锁。
            oneThread.stopThreadA();
        }
    /**
         * 运行实现Runnable接口定义的线程
         */
        public void startTwo() {
            // 创建实例
            Runnable runnable = new TwoThread();
            // 将实例放入到线程中
            Thread threadB = new Thread(runnable);
            // 启动线程
            threadB.start();
        }
    // 继承Thread类定义线程
    class OneThread extends Thread {
        private boolean running = false;
    
        public void start() {
            this.running = true;
            super.start();
        }
        public void run() {
            int i = 0;
            try {
                while (running) {
                    System.out.println("继承Thread类定义线程程序体......" + i++);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void startThreadA() {
            System.out.println("启动继承Thread类定义线程");
            this.start();
        }
        public void stopThreadA() {
            System.out.println("关闭继承Thread类定义线程");
            this.running = false;
        }
    }
    // 实现Runnable接口定义线程
    class TwoThread implements Runnable {
        private Date runDate;
    
        public void run() {
            System.out.println("实现Runnable接口定义线程程序体......");
            this.runDate = new Date();
            System.out.println("线程启动时间......" + runDate);
        }
    public static void main(String[] args) {
            // 实例化对象
            ThreadStartAndStop threadStartAndStop = new ThreadStartAndStop();
            threadStartAndStop.startOne();
            threadStartAndStop.startTwo();
        }

    启动继承Thread类定义线程 继承Thread类定义线程程序体......
    0 继承Thread类定义线程程序体......1 继承Thread类定义线程程序体......2 继承Thread类定义线程程序体......3 继承Thread类定义线程程序体......4 关闭继承Thread类定义线程 实现Runnable接口定义线程程序体...... 线程启动时间......Fri Mar 15 12:56:57 CST 2013
  • 相关阅读:
    前缀和
    B. Ilya and Queries
    BZOJ1652 [Usaco2006 Feb]Treats for the Cows
    NOIP2014提高组 酱油记
    NOIP初赛 BLESS ALL!
    BZOJ1096 [ZJOI2007]仓库建设
    BZOJ1036 [ZJOI2008]树的统计Count
    BZOJ1030 [JSOI2007]文本生成器
    BZOJ2749 [HAOI2012]外星人
    BZOJ1093 [ZJOI2007]最大半连通子图
  • 原文地址:https://www.cnblogs.com/zjwia/p/2961503.html
Copyright © 2020-2023  润新知