欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 13:51:40
thread和runnable区别 执行多线程操作可以选择 继承thread类 实现runnable接口 1.继承thread类 以卖票窗口举例,一共5张票,...

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

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的区别详解整合,希望对大家有所帮助