什么是进程,什么是线程这里就不做赘述了,直接进入主题。
首先介绍一下一般程序的运行顺序,如图:
包括一个入口,一个出口和一个顺次执行的语句序列。
而包含线程对象的程序的执行顺序是:
线程与主线程共享CPU资源(交替使用)
线程一共有四种状态:新建(new),可运行(runnable),死亡(dead)以及阻塞(blocked)。
1. 创建线程
创建线程一般有两种方法:
1.1 继承 Thread 类并重写其中的 run() 方法
//定义一个线程类,它继承Thread类
class test_thread extends Thread {
//重写run()方法
public void run() {
for (int i = 0; i != 100; ++i) {
System.out.println("SubThread_1: " + i);
}
}
}
1.2 实现 Runnable 接口
//定义一个线程类,实现Runnable接口
class Runner implements Runnable {
//实现run()方法
public void run() {
for (int i = 0; i != 100; ++i) {
System.out.println("SubThread_2: " + i);
}
}
}
2. 线程的状态
2.1 新建(new)
//新建一个线程
Thread thread = new Thread("test");
2.2 可运行状态(runnable)
//可运行状态
thread.start();
2.3 死亡(dead)
//死亡,stop()函数不安全,不建议使用
thread.stop();
2.4 阻塞(blocked)
//阻塞
try {
//以毫秒为单位
Thread.sleep(100);
} catch(InterruptedException e) {}
2.5 中断线程
//中断线程
thread.interrupt();
3. 线程的调度
public static void main(String[] args) {
//创建线程对象tt
test_thread tt = new test_thread();
//启动线程对象tt
tt.start();
//创建Runner类对象r
Runner r = new Runner();
//创建线程对象t,参考构造方法Thread(Runnable target)
Thread t = new Thread(r);
//启动线程对象t
t.start();
//主线程
for(int i = 0; i != 100; ++i) {
System.out.println("MainThread: " + i);
}
}
4. 运行结果
可以看到各条线程明显的交替运行,交替占用CPU资源,实现"并行性"。