目录
线程概述
进程:进程通俗的来说就是一个程序的执行过程,进程是动态的。
程序:静态代码段,是一组指令的有序集合。
线程:线程就是进程里面的一个执行路径。
多线程:多线程是为了同步完成多项任务,不是为了提高运行效率,而是为了提高资源使用效率来提高系统的效率。线程是在同一时间需要完成多项任务的时候实现的。
线程的运行
- 在单处理器是串行运行的。
- 在多处理器是并行运行的。
线程的两种创建方式
继承的方式
创建一个继承于Thread类的子线程,重写run方法。
我们从源码来看一下创建线程的过程。(源码基于jdk 1.7.81)
public class Thread implements Runnable
我们可以看到这是 Thread 类的方法头。它继承自Runnable 接口
从下面代码可以看到Runnable 接口只有一个 run 方法。Thread必须要重写run方法。
package java.lang;
public interface Runnable {
public abstract void run();
}
下面这是Thread 的初始化,Thread 的所有构造方法都是基于这个方法。可以看到初始化的参数里面有一个Runnable 的对象,创建线程的关键就是这个对象。默认情况下这个参数为NULL.
/**
* Initializes a Thread.
*
* @param g 线程组
* @param target runnable对象
* @param name 线程名
* @param stackSize 栈容量
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
下面这两个方法很重要, start 为native 方法,作用是启动这个线程,run方法为线程的入口点,从代码中我们可以看出run方法调用的是Runnable类的run方法,但Runnable 并没有实现这个方法,所以我们必须重写Thread 的run方法。
private native void start0();
public void run() {
if (target != null) {
target.run();
}
}
下面这个例子来帮助大家理解一下继承方式实现多线程。
class ThreadTest extends Thread{
public void run(){
for(int i = 0;i < 3;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
//主函数
public class Demo1 {
public static void main(String[] args) {
ThreadTest thread1 = new ThreadTest();
ThreadTest thread2 = new ThreadTest();
thread1.start();
thread2.start();
}
}
实现的方式
从继承的方式我们看出线程的实现更倚重于Runnable 接口,我们不妨自己写一个实现了Runnable 接口的类。
Thread2 直接继承自Runnable 接口并实现其run方法,在主函数里我们新建两个线程分别为t1,t2,它们传的参数的Runnable对象是同一个对象b。
class Thread2 implements Runnable{
public void run() {
for(int i = 0;i < 10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
public class Demo3 {
public static void main(String[] args) {
Thread2 b = new Thread2();
Thread t1 = new Thread(b);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}