【多线程】线程的创建

编程入门 行业动态 更新时间:2024-10-14 16:19:55

【多<a href=https://www.elefans.com/category/jswz/34/1771240.html style=线程】线程的创建"/>

【多线程】线程的创建

创建线程如下几个方法:

目录

继承Thread类

调用start方法启动线程

调用run方法

实现Runnable接口

实现Callable接口


继承Thread类

调用start方法启动线程

public class TestThread extends Thread{//继承Thread类//重写run方法public void run(){for(int i=0;i<5;i++){System.out.println("你好");}}public static void main(String[] args) {//main线程  主线程//创建一个线程对象TestThread testThread=new TestThread();//调用start方法testThread.start();for(int i=0;i<5;i++){System.out.println("我在学习多线程");}}
}

 预期结果是两个线程同时进行,交替进行

调用run方法

通常需要重写Thread类中的此方法.将创建的线程要执行的操作声明在此方法中

public class TestThread extends Thread{//继承Thread类//重写run方法@Overridepublic void run(){for(int i=0;i<200;i++){System.out.println("你好");}}public static void main(String[] args) {//main线程  主线程//创建一个线程对象TestThread testThread=new TestThread();//调用run方法testThread.run();for(int i=0;i<500;i++){System.out.println("我在学习多线程");}}
}

 预期结果:先进行run方法,输出(你好),后输出(我在学习多线程)

实现Runnable接口

1.定义MyRunnable类实现Runnable接口

2.实现run(),编写线程执行体

3.创建线程对象,调用start()方法启动线程

package org.example;//调用Runnable接口,重写run方法
public class TestRunable implements Runnable {//继承Thread类//重写run方法@Overridepublic void run(){for(int i=0;i<200;i++){System.out.println("你好");}}public static void main(String[] args) {//main线程  主线程//创建一个Runnable接口的实现类对象TestRunnable teatRunnable=new TestRunnable();//创建线程对象,通过线程对象开启线程Thread thread=new Thread(test2Thread);thread.start();for(int i=0;i<500;i++){System.out.println("我在学习多线程");}}
}

实现Callable接口

package org.example;import java.util.concurrent.*;public class TestCallable implements Callable<String> {private int num;private String text;public TestCallable(int num, String text) {this.num=num;this.text=text;}@Overridepublic String call() {TextPrint textPrint=new TextPrint();textPrint.Print(num,text);return "Hello World";}public static void main(String[] args) throws ExecutionException, InterruptedException {//创建callable接口的实现类对象TestCallable t1=new TestCallable(1,"我在");TestCallable t2=new TestCallable(1,"学习");TestCallable t3=new TestCallable(1,"多线程");//创建执行服务ExecutorService ser= Executors.newFixedThreadPool(3);//提交执行Future<String> r1=ser.submit(t1);Future<String> r2=ser.submit(t2);Future<String> r3=ser.submit(t3);//获取结果String a1=r1.get();String a2=r2.get();String a3=r3.get();/*//关闭服务ser.shutdownNow();*/}class   TextPrint {public void Print(int num, String text) {for (int i = 0; i < num; i++) {System.out.println(text);}}
}
}

得到一个多线程的结果

 

更多推荐

【多线程】线程的创建

本文发布于:2023-11-16 17:48:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   多线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!