继承thread类
实现runnable类
-------------------------------------------------------------------------------------
1. 继承thread类
继承thread类之后,需要覆盖父类的 public void run() 方法,作为线程的主方法。
所有线程的执行一定是并发的,即:同一个时间段上会有多个线程交替执行。为了达到这样的目的,绝对不能直接调用run()方法,而是应该调用thread类的start()方法启动多线程。
调用 start() 方法和调用 run() 方法的对比:
public class mythread extends thread { private string name; public mythread(string name) { this.name = name; } @override public void run() { for(int i=0; i<10; i++) { system.out.println(name + "打印:" + i); } } public static void main(string[] args) { mythread mt1 = new mythread("线程a"); mythread mt2 = new mythread("线程b"); mythread mt3 = new mythread("线程c"); mt1.start(); mt2.start(); mt3.start(); } }
运行结果:(三个线程同时且交替执行,没有固定的执行顺序)
public class mythread extends thread { private string name; public mythread(string name) { this.name = name; } @override public void run() { for(int i=0; i<5; i++) { system.out.println(name + "打印:" + i); } } public static void main(string[] args) { mythread mt1 = new mythread("线程a"); mythread mt2 = new mythread("线程b"); mythread mt3 = new mythread("线程c"); mt1.run(); mt2.run(); mt3.run(); } }
运行结果:(三个程序依次顺序执行)
2. start()方法实现多线程的原理
打开thread类源代码中start()方法的部分:
public synchronized void start() { if (threadstatus != 0) throw new illegalthreadstateexception(); group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadstartfailed(this); } } catch (throwable ignore) { } } } private native void start0();
native关键字是指调用操作系统的方法,start0()方法是所在操作系统的方法。
由于线程的启动需要牵扯到操作系统中资源的分配问题,所以具体的线程的启动应该根据不同的操作系统有不同的实现。而jvm根据不同的操作系统中定义的start0()方法进行不同的实现。这样,在多线程的层次上start0()方法的名称不改变,而不同的操作系统有不同的实现。
原理图
结论:只有thread类的start()方法才能进行操作系统资源的分配,所以启动多线程的方式永远就是thread类的start()方法。
