runable和thread的区别

  使用runable进行测试:

class MyRunnable implements Runnable{
   private int ticket=10;
   public void run(){
	   for(int i=0;i<20;i++)
	   {
		   if(this.ticket>0){
			   System.out.println("卖票:ticket"+this.ticket--);
	      }
       }
   }
}
测试类:

public class ThreadDemo01{
	public static void main(String[] args) {
		    MyRunnable  r1=new MyRunnable();
			Thread t1=new Thread(r1);
			Thread t2=new Thread(r1);
			t1.start();
			t2.start();
	}
}

2个线程,一共卖出10张票:

卖票:ticket10
卖票:ticket9
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1
卖票:ticket8

使用Thread进行测试:

class MyThread extends Thread{
	   private int ticket=10;
	   public void run(){
		   for(int i=0;i<20;i++)
		   {
			   if(this.ticket>0){
				   System.out.println("卖票:ticket"+this.ticket--);
		      }
	       }
	   }
}

public class ThreadDemo02{
	public static void main(String[] args) {
		    MyThread mt=new MyThread();
			Thread t1=new Thread(mt);
			Thread t2=new Thread(mt);
			t1.start();
			t2.start();
	}
}
2个线程,依然卖出10张票

卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1
           总结:个人认为继承thread类和实现runnable接口,能达到同样的效果。唯一区别是,实现接口更灵活,继承只能单继承。

问题:按理说,两个线程访问同一个共享变量ticket,一般要加锁才可以达到同步效果。这里为什么可以不用加锁呢?如果在run方法上,加锁肯定也是对的。

posted @ 2017-10-12 21:31  cheerupWoo  阅读(146)  评论(0编辑  收藏  举报