详解多线程及Runable 和Thread的区别
程序员文章站
2023-12-16 23:36:10
thread和runnable区别
执行多线程操作可以选择
继承thread类
实现runnable接口
1.继承thread类
以卖票窗口举例,一共5张票,...
thread和runnable区别
执行多线程操作可以选择
继承thread类
实现runnable接口
1.继承thread类
以卖票窗口举例,一共5张票,由3个窗口进行售卖(3个线程)。
代码:
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张票"的初衷。
造成此现象的原因就是:
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接口
同样的例子,代码:
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张票。
原因在于:
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的区别详解整合,希望对大家有所帮助
推荐阅读
-
详解多线程及Runable 和Thread的区别
-
MYSQL 左连接右连接和内连接的详解及区别
-
Mybatis的mapper文件中$和#的用法及区别详解
-
jquery遍历之parent()和parents()的区别及parentsUntil()方法详解
-
Linux KVM的QCOW2 和 ROW的详解及区别介绍
-
解析PHP中VC6 X86和VC9 X86的区别及 Non Thread Safe的意思
-
MySQL中datetime和timestamp的区别及使用详解
-
详解python while 函数及while和for的区别
-
Git fetch和pull的详解及区别
-
Oracle call 和 exec的详解及区别