一. 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