Java并发编程之Java创建线程的三种方式(1),mysql集群架构部署方案

本文详细介绍了Java中线程的创建方法,包括继承Thread类和实现Runnable接口。通过实例展示了如何重写run()方法以执行特定任务。此外,还探讨了Callable接口及其call()方法,它允许返回值并使用FutureTask进行包装。最后,文章提到了使用Future获取call()方法的返回值的过程,以及FutureTask内部的工作原理。
摘要由CSDN通过智能技术生成

}

}

public abstract void run();

如果在run()中没有要运行的程序,线程将在启动后直接死掉。如果希望线程执行某些操作,则必须重写run()方法。同时,应当注意,线程启动需要调用start()方法,但是对run()方法的直接调用也可以被编译并正确运行。

public static void main(String[] args) {

Thread thread = new ThreadDemo();

thread.run();

}

But this is a common method call, and there is no new thread, so it loses the meaning of the thread itself.

二、实现Runnable接口

1、定义一个线程类来实现Runnable接口,并重写接口的run()方法,该方法仍然包含指定要执行的程序。

2、创建一个Runnable实现类实例,将其作为目标参数传递,并创建一个Thread类实例。3、调用Thread类实例的start()方法来启动线程。

public class RunnableDemo implements Runnable{

@Override

public void run() {

System.out.println(“我是Runnable接口…”);

}

public static void main(String[] args) {

RunnableDemo demo = new RunnableDemo();

Thread thread = new Thread(demo);

thread.start();

}

}

这是一种基于接口的方法,比继承Thread灵活得多,但是它需要创建一个更线程化的对象。打开源代码,可以发现当Runnable实现类的实例作为参数目标传入时,它被分配给当前线程类的目标,而在run()中执行的程序是分配给该目标的run()方法。

public Thread(Runnable target) {

init(null, target, “Thread-” + nextThreadNum(), 0);

}

private void init(ThreadGroup g, Runnable target, String name,

long stackSize, AccessControlContext acc) {

…这里省略部分源码…

this.target = target;

setPriority(priority);

if (parent.inheritableThreadLocals != null)

this.inheritableThreadLocals =

ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

/* Stash the specified stack size in case the VM cares */

this.stackSize = stackSize;

/* Set thread ID */

tid = nextThreadID();

}

@Override

public void run() {

if (target != null) {

target.run();

}

}

三、使用Callable和Future创建线程

使用Callable创建线程类似于使用Runnable接口创建线程。区别在于Callable接口提供call()方法作为线程执行器,而Runnable接口提供run()方法。同时,call()方法可以具有返回值,并且需要FutureTask类来包装Callable对象。

public interface Callable {

V call() throws Exception;

}

步骤:

1、创建Callable接口的实现类,实现call() 方法

2、创建Callable实现类实例,通过FutureTask类来包装Callable对象,该对象封装了Callable对象的call()方法的返回值。

3、将创建的FutureTask对象作为target参数传入,创建Thread线程实例并启动新线程。4、调用FutureTask对象的get方法获取返回值。

执行main方法后,程序输出如下结果:

task 返回值为:1

注意这个任务。get()返回call()方法的结果。那么它在内部是如何工作的呢?首先打开FutureTask的构造方法,可以看到Callable对象作为参数传递给当前实例的Callable成员。

public FutureTask(Callable callable) {

if (callable == null)

throw new NullPointerException();

this.callable = callable;

this.state = NEW;       // ensure visibility of callable

}

同时,将成员变量状态设置为NEW。当任务启动时,它的run方法执行Callable的call()方法。

public void run() {

if (state != NEW ||

!UNSAFE.compareAndSwapObject(this, runnerOffset,

null, Thread.currentThread()))

return;

try {

Callable c = callable;

if (c != null && state == NEW) {

V result;

boolean ran;

try {

//把call()的返回结果复制给result

result = c.call();

ran = true;

} catch (Throwable ex) {

result = null;

ran = false;

setException(ex);

}

if (ran)

//将结果设置给其他变量

set(result);

}

} finally {

// runner must be non-null until state is settled to

// prevent concurrent calls

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

to run()

runner = null;

// state must be re-read after nulling runner to prevent

// leaked interrupts

int s = state;

if (s >= INTERRUPTING)

handlePossibleCancellationInterrupt(s);

}

}

protected void set(V v) {

if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {

//把传过来的值赋值给outcome成员

outcome = v;

UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state

finishCompletion();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值