实例分析Java单线程与多线程

2025-05-29 0 33

线程:每一个任务称为一个线程,线程不能独立的存在,它必须是进程的一部分

单线程:般常见的Java应用程序都是单线程的,比如运行helloworld的程序时,会启动jvm进程,然后运行main方法产生线程,main方法也被称为主线程。

多线程:同时运行一个以上线程的程序称为多线程程序,多线程能满足程序员编写高效率的程序来达到充分利用 CPU 的目的。

单线程代码例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
public class SingleThread {

public static void main(String[] args){

Thread thread = Thread.currentThread(); //获取当前运行的线程对象

thread.setName("单线程"); //线程重命名

System.out.println(thread.getName()+"正在运行");

for(int i=0;i<10;i++){

System.out.println("线程正在休眠:"+i);

try {

thread.sleep(1000); //线程休眠,延迟一秒

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println("线程出错");

}

}

}

}

多线程代码例子:

注意:多线程有两种实现方式,一种是继承Thread类,另一种是实现Runnable接口。

继承Thread类实现多线程

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28
public class TestThread {

public static void main(String[] args){

Thread t1 = new ExtendThread("t1",1000); //使用上转对象创建线程,并构造线程名字和线程休眠时间

Thread t2 = new ExtendThread("t2",2000);

Thread t3 = new ExtendThread("t3",3000);

t1.start(); //启动线程并调用run方法

t2.start();

t3.start();

}

}

class ExtendThread extends Thread{ //继承Thread的类

String name;

int time;

public ExtendThread(String name, int time) { //构造线程名字和休眠时间

this.name=name;

this.time=time;

}

public void run(){ //重写Thread类的run方法

try{

sleep(time); //所有线程加入休眠

}

catch(InterruptedExceptione){

e.printStackTrace();

System.out.println("线程中断异常");

}

System.out.println("名称为:"+name+",线程休眠:"+time+"毫秒");

}

}

实现Runnable接口的多线程

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34
public class RunnableThread {

public static void main(String[] args){

Runnable r1=new ImplRunnable("r1",1000); //Runnable接口必须依托Thread类才能创建线程

Thread t1=new Thread(r1); //Runnable并不能调用start()方法,因为不是线程,所以要用Thread类加入线程

Runnable r2=new ImplRunnable("r2",2000);

Thread t2=new Thread(r2);

Runnable r3=new ImplRunnable("r3",3000);

Thread t3=new Thread(r3);

t1.start(); //启动线程并调用run方法

t2.start();

t3.start();

}

}

class ImplRunnable implements Runnable{ //继承Runnable接口的类

String name;

int time;

public ImplRunnable(String name, int time) { //构造线程名字和休眠时间

this.name = name;

this.time = time;

}

@Override

public void run() { //实现Runnable的run方法

try{

Thread.sleep(time); //所有线程加入休眠

}

catch(InterruptedException e){

e.printStackTrace();

System.out.println("线程中断异常");

}

System.out.println("名称为:"+name+",线程休眠:"+time+"毫秒");

}

}

说明:Thread类实际上也是实现了Runnable接口的类。

实现Runnable接口比继承Thread类所具有的优势

原文链接:https://www.idaobin.com/archives/807.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 实例分析Java单线程与多线程 https://www.kuaiidc.com/112140.html

相关文章

发表评论
暂无评论