zoukankan      html  css  js  c++  java
  • Java中创建多线程

    Java中创建新线程有多种方式,一般从Thread派生一个自定义类,然后覆写run方法,或者创建Thread实例时,传入一个Runnable实例。两种方式可通过内部匿名类或者lambda语法进行简写。

    1、通常写法

    class MyTheard extends Thread {
        @Override
        public void run() {
            System.out.println("new thread created by extends thread");
        }
    }
    
    class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("new thread created by implements runnable");
        }
    }
    Thread t1 = new MyTheard();
    Thread r1 = new Thread(new MyRunnable());
    t1.start();
    r1.start();

    2、使用内部匿名类简写

    Thread t2 = new Thread() {
        @Override
        public void run() {
            System.out.println("new thread created by extends thread using Anonymous class");
        }
    };
    
    Runnable r2 = new Runnable() {
        @Override
        public void run() {
            System.out.println("new thread created by implements runnable using Anonymous class");
        }
    };
    t2.start();
    new Thread(r2).start();

    3、使用lambda语法

    Thread t3 = new Thread(()-> {
        System.out.println("new thread created by extends thread using lambda");
    });
    
    Runnable r3 = ()-> {
        System.out.println("new thread created by implements runnable using lambda");
    };
    t3.start();
    new Thread(t3).start();

     使用简化的语法,减少了代码量,并且无需定义子类名,解决了命名难的问题。

    参考链接

    https://www.liaoxuefeng.com/wiki/1252599548343744/1376414781669409

  • 相关阅读:
    oracle数据库根据年和月查询出表中 某年某月的数据信息
    分页问题,js之间比较不可以是字符串与字符串比较
    layer.load("试题分析中,可能需要一段时间,请稍后......",0);解析
    编译java程序
    java语言特性
    JDK
    超链接样式属性
    背景样式
    表格合并操作
    表单
  • 原文地址:https://www.cnblogs.com/engeng/p/15538830.html
Copyright © 2011-2022 走看看