zoukankan      html  css  js  c++  java
  • 多线程005创建线程有哪些方式

    创建线程的四种方式

    (1)继承Thread类

    (2)实现Runnable接口

    (3)实现Callable接口

    (4)使用线程池

     1 package com.example.concurrency;
     2 
     3 import java.util.concurrent.Callable;
     4 import java.util.concurrent.ExecutionException;
     5 import java.util.concurrent.Executor;
     6 import java.util.concurrent.ExecutorService;
     7 import java.util.concurrent.Executors;
     8 import java.util.concurrent.Future;
     9 import java.util.concurrent.FutureTask;
    10 //第一种:继承Thread类
    11 class MyThread extends Thread {
    12     public void run() {
    13         System.out.println("线程调用");
    14     }
    15 }
    16 
    17 //第二种,实现Runnable接口
    18 class MyRunnable implements Runnable {
    19     private Boolean tag = true;
    20 
    21     @Override
    22     public void run() {
    23         // TODO Auto-generated method stub
    24         int i = 0;
    25         while (tag) {
    26             System.out.println("线程调用:" + i++);
    27         }
    28     }
    29 
    30     public void stop() {
    31         this.tag = false;
    32     }
    33 }
    34 
    35 //第三种:实现Callable接口
    36 class MyCallable implements Callable<Integer> {
    37 
    38     @Override
    39     public Integer call() throws Exception {
    40         // TODO Auto-generated method stub
    41         System.out.println("线程调用,返回123");
    42         return 123;
    43     }
    44 
    45 }
    46 
    47 //创建线程的四种方式
    48 public class demo05 {
    49 
    50     public static void main(String[] args) throws InterruptedException, ExecutionException {
    51         // 方式一:继承Thread类
    52         MyThread thread3 = new MyThread();
    53         thread3.start();
    54 
    55         // 方式二:实现Runnable接口
    56         MyRunnable instance = new MyRunnable();
    57         Thread thread = new Thread(instance);
    58         thread.start();
    59 
    60         // 方式三-实现Callable接口:
    61         MyCallable mc = new MyCallable();
    62         FutureTask<Integer> ft = new FutureTask<Integer>(mc);
    63         Thread thread2 = new Thread(ft);
    64         thread2.start();
    65 
    66         // 方式四-使用线程池:
    67         ExecutorService ser = Executors.newFixedThreadPool(1);// 线程池
    68         Future<Integer> ft2 = ser.submit(mc);// 执行线程
    69         Integer result = ft2.get();// 获取结果
    70         ser.shutdown();// 关闭
    71     }
    72 }
  • 相关阅读:
    商业模式--资源整合
    “不小心出卖了领导”
    计算机禁用桌面并且禁用键盘Win+*快捷键组合之后如何打开文件资源管理器
    spring-boot 参数长度、文件上传大小限制问题
    Python 学习基础
    Python字典详解
    Python元组
    Python列表详解
    Python变量类型
    Python字符串详解
  • 原文地址:https://www.cnblogs.com/asenyang/p/15568169.html
Copyright © 2011-2022 走看看