本篇文章给大家带来的内容是关于java中的多线程如何创建?(详细),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
什么是线程:
线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源
表面上是多线程其实是cpu快速轮流切执行
多线程(并行和并发)
并行:两个任务同事进行,就是甲任务执行的同时,乙任务也在执行(需要多核)
并发:两个任务都请求运行,而处理器只能接受一个任务,就把这两个任务安排轮流执行。由于时间间隔很短,使人感觉两个任务都在运行
多线程(java程序运行的原理)
java命令会启动jvm等于启动了一个应用程序(一个进程)。该进程会自动启动“主线程”,主线程去调用main方法
启动jvm是单线程的么?
不是,是多线程的。至少会启动垃圾回收线程和主线程
可通过下面代码来验证,主线程和垃圾回收线程在互相抢占资源
public class TestThread { public static void main(String[] args) { //4.创建Thread的子类对象 MyThread myThread = new MyThread(); //5.启动线程,注意这里使用的是start而不是run方法 myThread.start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } //1.继承Thread class MyThread extends Thread{ //2.重写run方法 @Override public void run() { super.run(); //3.线程方法中要执行的代码,可以根据自己的需求填写 for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyThread thread "); } } }
java中如何创建多线程
(1)继承Thread类并调用start方法
Thread实现了Runnable接口
要实现多线程,就要成为thread的子类,并且重写run方法。注意在启动线程的时候,调用的不是run方法而是start方法。如果调用run方法,那么相当于一个普通方法并不会开启线程
public class Thread implements Runnable
public class TestThread { public static void main(String[] args) { MyThread myThread = new MyThread(); //注意这里使用的是start而不是run方法 myThread.start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } class MyThread extends Thread{ @Override public void run() { super.run(); for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyThread thread "); } } }
(2)实现runnable接口,并重写run方法
Runnable中只有一个方法run(),而线程启动方法存在与Thread中,
那么我们在最终启动线程的时候,势必是要通过Thread的子类对象去启动线程的
public class TestRunnable { public static void main(String[] args) { //4.创建Thread的子类对象 Runnable myRunnable = new MyRunnable(); //5.启动线程,创建Thread并把runnable的子类作为构造参数 new Thread(myRunnable).start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } //1.实现runnable接口 class MyRunnable implements Runnable { //2.重写run方法 @Override public void run() { //3.线程方法中要执行的代码,可以根据自己的需求填写 for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyRunnable thread "); } } }
实现Callable接口
要实现线程,除了继承thread和runnable,还可以实现Callable接口。Callable接口提供了一个call()方法可以作为线程执行体,和run()的作用一样。但call()方法比run()方法多了返回值,call()方法可以声明抛出的异常。那么我们如何开启Callable线程呢?因为Callable接口不是Runnable接口的子接口,所以Callable对象不能作为Thread的构造参数。Java提供了另一个接口RunnableFuture接口,该接口实现了Runnable, Future
实现Callable接口
重写call方法,相当于thread中的run方法。不同的是call方法允许有返回值
把Callable实现类对象作为构造参数传入FutureTask创建FutureTask对象。
把FutureTask对象作为构造参数传入Thread,并开启线程
public class CallableDemo { public static void main(String[] args) { //3.把Callable实现类对象作为构造参数传入FutureTask创建FutureTask对象。 FutureTask<UUID> futureTask = new FutureTask<UUID>(new MyCallable()); //4.把FutureTask对象作为构造参数传入Thread,并开启线程 new Thread(futureTask).start(); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } //1. 实现**Callable**接口 class MyCallable implements Callable<UUID> { //2.重写**call**方法,相当于thread中的run方法。不同的是call方法允许有返回值 @Override public UUID call() throws Exception { //生成随机数 return UUID.randomUUID(); } }
继承Thread,实现Runnable和Callable的区别
从源码的实现上
继承Thread
子类重写Thread中的run()方法,调用start()方法,jvm会自动调用子类的run()
实现Runnable
new Thread(myRunnable)在Thread的构造函数中参入runnable的引用,然后传给thread的成员变量target。在Thread run()方法中判断了如果target不为空,就调用子类的run方法
public void run() { if (this.target != null) { this.target.run(); }
实现Callable接口
实现Callable接口重写Call()方法,并且可以提供线程返回值,也可以抛出异常。最终通过Runnable的子接口RunnableFuture的实现类FutureTask,传给Thread的成员变量target。
从使用上和拓展上
继承Thread
优点:直接调用thread中的start()方法,十分简单
缺点:java只支持单继承,如果子类继承了thread无法再继承其他类
实现Runnable
优点:java可以多实现
缺点:代码书写比较复杂,不能直接调用start()
实现Callable
优点:java可以多实现,可以抛出异常,可以有返回值
缺点:代码书写比较复杂
以上是java中的多线程如何创建?(详细)的详细内容。更多信息请关注PHP中文网其他相关文章!

JVM通过JavaNativeInterface(JNI)和Java标准库处理操作系统API差异:1.JNI允许Java代码调用本地代码,直接与操作系统API交互。2.Java标准库提供统一API,内部映射到不同操作系统API,确保代码跨平台运行。

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

javaachievesplatformIndependencEthroughThoJavavIrtualMachine(JVM),wodecutesbytecodeonyanydenanydevicewithajvm.1)javacodeiscompiledintobytecode.2)

JavaGUI开发中的平台独立性面临挑战,但可以通过使用Swing、JavaFX,统一外观,性能优化,第三方库和跨平台测试来应对。JavaGUI开发依赖于AWT和Swing,Swing旨在提供跨平台一致性,但实际效果因操作系统不同而异。解决方案包括:1)使用Swing和JavaFX作为GUI工具包;2)通过UIManager.setLookAndFeel()统一外观;3)优化性能以适应不同平台;4)使用如ApachePivot或SWT的第三方库;5)进行跨平台测试以确保一致性。

JavadevelovermentIrelyPlatForm-DeTueTososeVeralFactors.1)JVMVariationsAffectPerformanceNandBehaviorAcroSsdifferentos.2)Nativelibrariesviajnijniiniininiinniinindrododerplatefform.3)

Java代码在不同平台上运行时会有性能差异。1)JVM的实现和优化策略不同,如OracleJDK和OpenJDK。2)操作系统的特性,如内存管理和线程调度,也会影响性能。3)可以通过选择合适的JVM、调整JVM参数和代码优化来提升性能。

Java'splatFormentenceHaslimitations不包括PerformanceOverhead,versionCompatibilityIsissues,挑战WithnativelibraryIntegration,Platform-SpecificFeatures,andjvminstallation/jvminstallation/jvmintenance/jeartenance.therefactorscomplicatorscomplicatethe“ writeOnce”


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具