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 }
  • 相关阅读:
    需要返回对象时候,不要以引用形式返回
    成对使用new和delete,传值传引用
    赋值重载的约定(1)
    oracle操作字符串:拼接、替换、截取、查找
    Oracle CASE WHEN 用法介绍
    oracle中如何对字符串进行去除空格的方法
    日期显示
    Oracle Cursor用法总结
    每天一个linux命令(26):用SecureCRT来上传和下载文件
    每天一个linux命令(25):linux文件属性详解
  • 原文地址:https://www.cnblogs.com/asenyang/p/15568169.html
Copyright © 2011-2022 走看看