线程创建
Posted w-ting
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程创建相关的知识,希望对你有一定的参考价值。
三种方式:
1.通过继承Thread 重写run方法,
public class HelloWordThread extends Thread { @Override public void run(){ System.out.println("hello world!!!!!!!!"); } public static void main(String[] args) { System.out.println("开始----"); HelloWordThread helloWordThread = new HelloWordThread(); System.out.println("启动----"); helloWordThread.start(); } }
2.通过实现runable 重写run方法
public class HelloWorldRunable implements Runnable{ public void run() { System.out.println("hello world ----------"); } public static void main(String[] args) { System.out.println("开始---"); HelloWorldRunable helloWorldRunable = new HelloWorldRunable(); System.out.println("启动---"); helloWorldRunable.run(); } }
3.通过 实现 Callable 使用FutureTask 对象,可以传参数以及获取返回值
public class HelloWorldCallable implements Callable<Integer>{ private int i ; public HelloWorldCallable(int i){ this.i = i; } @Override public Integer call() throws Exception { System.out.println("参数::i=="+i); return this.i; } public static void main(String[] args) { //FutureTask 对象 //无参数 FutureTask task = new FutureTask(() -> { int count = 0; for (int i = 0; i <= 100; i++) { count += i; } return count; }); //创建线程 Thread thread = new Thread(task); thread.start(); try { System.out.println("无参数:::"+task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } //带参数 FutureTask task1 = new FutureTask(new HelloWorldCallable(100)); Thread thread1 = new Thread(task1); try { System.out.println("带参数::i=="+task1.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
以上是关于线程创建的主要内容,如果未能解决你的问题,请参考以下文章