详解多线程及Runable 和Thread的区别

2025-05-29 0 29

详解多线程及Runable 和Thread的区别

thread和runnable区别

执行多线程操作可以选择
继承thread
实现runnable接口

1.继承thread

以卖票窗口举例,一共5张票,由3个窗口进行售卖(3个线程)。
代码:

?

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
package thread;

public class threadtest {

public static void main(string[] args) {

mythreadtest mt1 = new mythreadtest("窗口1");

mythreadtest mt2 = new mythreadtest("窗口2");

mythreadtest mt3 = new mythreadtest("窗口3");

mt1.start();

mt2.start();

mt3.start();

}

}

class mythreadtest extends thread{

private int ticket = 5;

private string name;

public mythreadtest(string name){

this.name = name;

}

public void run(){

while(true){

if(ticket < 1){

break;

}

system.out.println(name + " = " + ticket--);

}

}

}

执行结果:
窗口1 = 5
窗口1 = 4
窗口1 = 3
窗口1 = 2
窗口1 = 1
窗口2 = 5
窗口3 = 5
窗口2 = 4
窗口3 = 4
窗口3 = 3
窗口3 = 2
窗口3 = 1
窗口2 = 3
窗口2 = 2
窗口2 = 1
结果一共卖出了5*3=15张票,这违背了"5张票"的初衷。
造成此现象的原因就是:

?

1

2

3

4

5

6
mythreadtest mt1 = new mythreadtest("窗口1");

mythreadtest mt2 = new mythreadtest("窗口2");

mythreadtest mt3 = new mythreadtest("窗口3");

mt1.start();

mt2.start();

mt3.start();

一共创建了3个mythreadtest对象,而这3个对象的资源不是共享的,即各自定义的ticket=5是不会共享的,因此3个线程都执行了5次循环操作。

2.实现runnable接口

同样的例子,代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
package thread;

public class runnabletest {

public static void main(string[] args) {

myrunnabletest mt = new myrunnabletest();

thread mt1 = new thread(mt,"窗口1");

thread mt2 = new thread(mt,"窗口2");

thread mt3 = new thread(mt,"窗口3");

mt1.start();

mt2.start();

mt3.start();

}

}

class myrunnabletest implements runnable{

private int ticket = 5;

public void run(){

while(true){

if(ticket < 1){

break;

}

system.out.println(thread.currentthread().getname() + " = " + ticket--);

}

}

}

结果:

窗口1 = 5
窗口1 = 2
窗口3 = 4
窗口2 = 3
窗口1 = 1

结果卖出了预期的5张票。
原因在于:

?

1

2

3

4

5

6

7
myrunnabletest mt = new myrunnabletest();

thread mt1 = new thread(mt,"窗口1");

thread mt2 = new thread(mt,"窗口2");

thread mt3 = new thread(mt,"窗口3");

mt1.start();

mt2.start();

mt3.start();

只创建了一个myrunnabletest对象,而3个thread线程都以同一个myrunnabletest来启动,所以他们的资源是共享的。

以上所述是小编给大家介绍的多线程及runable 和thread的区别详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://blog.csdn.net/qq_43499096/article/details/89048216

收藏 (0) 打赏

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

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

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

快网idc优惠网 建站教程 详解多线程及Runable 和Thread的区别 https://www.kuaiidc.com/109447.html

相关文章

发表评论
暂无评论