标签:
一,多线程
多线程是提高程序效率,避免资源浪费的很好的解决方案,下面来慢慢的介绍多线程的一些基本知识,而这些是晋级高级不可或缺的一部分
1,Thread类
类实现多线程需要实现Runnable接口,我们跟踪一下源码,如下所示:
public class Thread implements Runnable { /* Make sure registerNatives is the first thing <clinit> does. */ private static native void registerNatives(); static { registerNatives(); } ........ }
Thread类实现了Runnable的接口,然后我们来看一下Runnable接口里面有什么东西,如下所示,哦,原来就一个run方法
public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object‘s * <code>run</code> method to be called in that separately executing * thread. * <p> 意思是说,实现runnable的接口后的对象可以用来创建一个线程,并且这个线程是通过run方法来运行的 * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
那么回过头来看看,Thread类中的重写的这个run方法是什么?
/**注意,这个注释的意思是说当用一个单独的Runnable对象来构造Thread线程的时候,Runnbalb对象的run方法将会被调用,否则,这个方法不起任何作用 * If this thread was constructed using a separate * <code>Runnable</code> run object, then that * <code>Runnable</code> object‘s <code>run</code> method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of <code>Thread</code> should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }
那么,这个target是什么鬼?继续追踪
/* What will be run. */ private Runnable target;
好了,上面说的是背景知识,下面来真材实料吧。
初始化线程的方法有两个,
1,直接重写Thread类的run方法,注意,如果此时给Thread的构造函数传递一个Runnable对象,这个runnable对象的run方法不起任何作用,因为重写的run方法没有调用父类的run方法
2,直接给Thread传递一个runnable对象,调用对象的run方法
方法1:
Thread tr = new Thread(){ @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("thread test"); } } }; tr.start();
方法2:
Thread tr2 = new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("runnable test"); } } }){}; tr2.start();
针对方法1,我们这有一个小小的验证
当我们同时传递一个runnable对象和重写run方法时,结果会怎样呢?很明显,重写的run方法后,不会调用原来的那个target相关的操作了,也就是说传递进去的runnable没任何作用了,下面验证一下:
new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in runnbale"); } } }){ @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in thread"); } } }.start(); }
运行结果是:
in thread
in thread
in thread
in thread
in thread
in thread
in thread
二,定时器
标签:
原文地址:http://www.cnblogs.com/ningheshutong/p/5837239.html