zoukankan      html  css  js  c++  java
  • Runnable和Thread

    继承Thread类

    • 子类继承Thread类具备多线程能力
    • 启动线程:子类对象.start()
    • 不建议使用:避免OOP单继承局限性

    实现Runnable接口

    • 实现接口Runnable具有多线程能力
    • 启动线程: 传入目标对象+Tread对象 .start()
    • 推荐使用:避免单继承局限性,灵活方便,方便同一对象被多个线程使用
    package DemoThread;
    //多个线程同时操作同一个对象
    //买火车票的例子
    public class TestThread02 implements Runnable{
        //票数
        private int ticketNums=10;
    
        @Override
        public void run() {
            while (true) {
                if(ticketNums<=0){
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "票");
            }
            }
    
        public static void main(String[] args) {
            TestThread02 testThread02=new TestThread02();
            new Thread(testThread02,"阿优").start();
            new Thread(testThread02,"大黄").start();
            new Thread(testThread02,"小柔").start();
    
        }
    
    
    }

  • 相关阅读:
    linux 网络不通问题排查
    linux下挂载U盘
    git 详细教程网址
    字符串的全排列和组合算法
    D-BUS详细分析
    linux socket编程之TCP与UDP
    Linux下的 .o、.a、.so文件
    Fiddler HTTPS指南
    nm指令
    无法使用xcode打出ipa包的解决方法
  • 原文地址:https://www.cnblogs.com/IanIan/p/13769848.html
Copyright © 2011-2022 走看看