zoukankan      html  css  js  c++  java
  • 多线程基础一之(线程的3种实现方式)

    实现线程的三种方式:

       (1)继承Thread类,重写Run方法 

    class MyThreadDemo extends Thread {
    @Override
    public void run() {
    System.out.println("This is my Thread!");
    }
    public static void main(String[] args) {
    MyThreadDemo thread = new MyThreadDemo();
    thread.start();
    }
    }

    (2)实现Runnable接口,重写Run方法
    class RunnableThread implements Runnable{

    @Override
    public void run() {
    System.out.println("This is my RunnableThread!");
    }
    public static void main(String[] args) {
    Thread thread = new Thread(new RunnableThread());
    thread.start();
    }
    }
    (3)实现callable接口,重写call()方法,并带返回值
    public class CallableDemo implements Callable<String> {

    public static void main(String[] args) throws Exception{

    ExecutorService executorService = Executors.newCachedThreadPool();
    CallableDemo callableDemo = new CallableDemo();
    Future<String> future = executorService.submit(callableDemo);
    //call未执行完
    //放一些其他业务逻辑的处理
    System.out.println(future.get());//阻塞
    executorService.shutdown();
    }
    @Override
    public String call() throws Exception {
    return "String"+1;
    }
    }
     
  • 相关阅读:
    pyzabbix 接口使用
    lvs使用进阶
    lvs基础
    linux服务基础之nginx配置详解
    linux服务基础之编译安装nginx
    iptables (二) nat & tcp_wrapper
    iptables (一) 主机防火墙和网络防火墙
    rsyslog及loganalyzer
    linux基础之Mini Linux制作
    linux基础之磁盘管理与文件系统
  • 原文地址:https://www.cnblogs.com/flgb/p/9902655.html
Copyright © 2011-2022 走看看