首页 > 编程语言 > 详细

Java 使用线程方式Thread和Runnable,以及Thread与Runnable的区别

时间:2016-12-30 17:00:15      阅读:214      评论:0      收藏:0      [点我收藏+]

一. java中实现线程的方式有Thread和Runnable

Thread:

public class Thread1 extends Thread{
	@Override
	public void run() {
		System.out.println("extend thread");
	}
}

 Runnable:

public class ThreadRunable implements Runnable{

	public void run() {
		System.out.println("runbale interfance");
		
	}
	
}

 使用

public static void main(String[] args) {
		new Thread1().start();
		new Thread(new ThreadRunable()).start();
	}

  

 

二.Thread和Runnable区别

 1.在程序开发中使用多线程实现Runnable接口为主。 Runnable避免继承的局限,一个类可以继承多个接口

 2. 适合于资源的共享

   如下面的例子   

public class TicketThread extends Thread{
	
	private int ticketnum = 10;
	
	@Override
	public void run() {
		for(int i=0; i<20;i++){
			if (this.ticketnum > 0) {
				ticketnum--;
				System.out.println("总共10张,卖掉1张,剩余" + ticketnum);
			}
		}
	}
}

  使用三个线程

public static void main(String[] args) {
		TicketThread tt1 = new TicketThread();
		TicketThread tt2 = new TicketThread();
		TicketThread tt3 = new TicketThread();
		tt1.start();
		tt2.start();
		tt3.start();
	}

  实际上是卖掉了30张车票

而使用Runnable,如下面的例子

public class TicketRunnableThread implements Runnable{

private int ticketnum = 10;
	
	public void run() {
		for(int i=0; i<20;i++){
			if (this.ticketnum > 0) {
				ticketnum--;
				System.out.println("总共10张,卖掉1张,剩余" + ticketnum);
			}
		}
	}
}

  使用三个线程调用

public static void main(String[] args) {
		TicketRunnableThread trt1 = new TicketRunnableThread();
		new Thread(trt1).start();
		new Thread(trt1).start();
		new Thread(trt1).start();
	}

  因为TicketRunnableThread是New了一次,使用的是同一个TicketRunnableThread,可以达到资源的共享。最终只卖出10张车票。

 

3.效率对比

public static void main(String[] args) {
	
		 long l1 = System.currentTimeMillis();

		    for(int i = 0;i<100000;i++){
		        Thread t = new Thread();
		    }

		    long l2 = System.currentTimeMillis();

		    for(int i = 0;i<100000;i++){
		        Runnable r = new Runnable() {
		            public void run() {
		            }
		        };
		    }

		    long l3 = System.currentTimeMillis();

		    System.out.println(l2 -l1);
		    System.out.println(l3 -l2);
	}

  在PC上的结果

119
5

  所以在使用Java线程池的时候,可以节约很多的创建时间

 

Java 使用线程方式Thread和Runnable,以及Thread与Runnable的区别

原文:http://www.cnblogs.com/linlf03/p/6237218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!