今天写下多线程,多线程是个老生常谈的知识,一谈及多线程,很多人就会想起多线程的实现方式,实现Runnable接口,或是实现Thread类。但是为什么这么就可以实现多线程呢?
我们通过代码来了解下吧!
public class ConcurrencyTest { private static final long count = 10000; public static void main(String[] args) throws InterruptedException { concurrency(); serial(); } private static void concurrency() throws InterruptedException{ long start = System.currentTimeMillis(); Thread thread = new Thread(new Runnable() { public void run() { int a =0; for(long i=0;i<count;i++){ a +=3; } } }); thread.start(); int b = 0; for(long i = 0;i<count;i++){ b--; } thread.join(); long time = System.currentTimeMillis()-start; System.out.print("concurrency:"+time+"ms,b="+b); } private static void serial(){ long start = System.currentTimeMillis(); int a = 0; for(long i = 0;i<count;i++){ a+=3; } int b = 0; for(long i=0;i<count;i++){ b--; } long time = System.currentTimeMillis()-start; System.out.print("serial:"+ time +"ms,b="+b+",a="+a); } }很多人都知道concurrency()方法使用的就是多线程,为什么呢?多线程到底是怎么创建的多个线程的呢?
我们来看下Runnable()接口的源码,
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> * 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(); }发现什么也没有,我们并没有获得有用的信息。
我们再来看下线程的start()方法的源码,
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } private native void start0();我们可以看到start()方法应该是通过start0()方法来实现多线程的,但是start0()的源码我们就看不到了,然后搜索下,start0方法用的native关键字,一个Native Method就是一个java调用非java代码的接口。一个Native Method是这样一个java的方法:该方法的实现由非java语言实现。