多线程系列一(入门)
本篇博客简单的说明了一下如何编写多线程代码以及如何应用Timer定时器。
示例一:创建三个简单的线程:
线程一:休眠0.5s打印当前线程的名字:
//创建第一个线程 Thread thread=new Thread(){ public void run(){ while(true){ try{ Thread.sleep(500); }catch(InterruptedExceptione){ e.printStackTrace(); } System.out.println("1:"+Thread.currentThread().getName());
} } }; thread.start(); |
线程二:同样是休眠0.5s打印当前线程的名字:
//创建第二个线程 Thread thread2=new Thread(new Runnable() {
@Override public void run() { while(true){ try{ Thread.sleep(500); }catch(InterruptedExceptione){ e.printStackTrace(); } System.out.println("2:"+Thread.currentThread().getName()); } } }); thread2.start(); |
线程三:同样是休眠0.5s打印当前线程的名字,此线程中父类本身runnable中有一个run方法,自己类中也有一个run方法。
//创建第三个线程 new Thread( new Runnable(){
@Override publicvoid run() { try{ Thread.sleep(500); }catch(InterruptedExceptione){ e.printStackTrace(); } System.out.println("runnable:"+Thread.currentThread().getName()); }
} ){ public void run(){
while(true){ try{ Thread.sleep(500); }catch(InterruptedExceptione){ e.printStackTrace(); } System.out.println("thread:"+Thread.currentThread().getName()); } }; }.start(); |
最后的输出结果为:
1:Thread-0 2:Thread-1 thread:Thread-2 1:Thread-0 2:Thread-1 thread:Thread-2 1:Thread-0 2:Thread-1 thread:Thread-2 1:Thread-0 2:Thread-1 thread:Thread-2 1:Thread-0 2:Thread-1 thread:Thread-2 |
分析:三个线程完成的功能都是一样的,第一个线程,是创建了一个Thread子类,第二个线程是传入了一个Runnable的参数,实现的Runnable的run方法,第三个线程中,当子类自己有run方法的时候执行自己的run方法,如果自己没有run方法才会去执行父类中的run方法。
示例二、应用Timer定时器:
应用1:创建一个定时器,10s之后开始执行,之后每隔3s执行一次:
public static void main(String[] args){ new Timer().schedule(new TimerTask(){
public void run(){ System.out.println("bombing!"); } },10000,3000); }
|
应用2:要求炸弹奇数的时候每隔2s爆炸一次,偶数的时候每隔4s爆炸一次。因为一个炸弹爆炸之后就没有了,所以需要一个自己的一个定时任务类来保证每次爆炸的炸弹不是同一个。然后用一个count变量来表示奇数或者偶数。
class MyTimerTaskextends TimerTask{ public void run(){ count=(count+1)%2; System.out.println("bombing!"); new Timer().schedule(new MyTimerTask(),2000+2000*count); } } new Timer().schedule(new MyTimerTask(),2000); while(true){ System.out.println(new Date(). try { Thread.sleep(1000); } catch (InterruptedExceptione) { e.printStackTrace(); } } |
运行的结果:
41 42 bombing! 43 44 45 46 bombing! 47 48 bombing! |
总结:
实现Runnable接口比继承Thread类所具有的优势:
1、可以共享同一个资源
2、可以避免单继承的限制
3、增加程序的健壮性
每个类中又会有一个main方法,其实每一个main方法启动的时候也是启动了一个线程,在java中每次启动线程都会启动两个线程,一个是main线程,一个是垃圾收集线程。Main线程也有可能在子线程结束之前结束,并且不会受影响,不会因为主线程的结束而结束。
能够实现定时任务的有很多工具,比如quartz框架,更简单易用的比如timer定时器,今天博客中示例中讲到了多线程如何使用timer。