1. 创建多线程 2 种方式
1. 继承 Thread
2. 实现 Runnable 接口
2. 继承 Thread 用法
- class MyThread extends Thread{
- private int ticketsCount= 5;// 一共 5 张火车票
- private String name;// 窗口 也是线程名字
- public MyThread(String name){
- this.name = name;
- }
- @Override
- public void run() {
- while (ticketsCount> 0){
- ticketsCount--; // 如果还有票 就卖掉一张
- System.out.println(name+"卖了 1 张票, 剩余票数为:"+ticketsCount);
- }
- }
- }
- public class TicketsThread {
- public static void main(String[] args){
- // 创建 3 个线程 模拟三个窗口卖票
- MyThread mt1 = new MyThread("窗口 1");
- MyThread mt2 = new MyThread("窗口 2");
- MyThread mt3 = new MyThread("窗口 3");
- // 启动这三个线程 , 也即是窗口 , 开始卖票
- mt1.start();
- mt2.start();
- mt3.start();
- }
- }
3. 实现 Runnable 用法
- class MyThreadRunnable implements Runnable {
- private int ticketsCount = 5 ;// 一共 5 张火车票
- @Override
- public void run() {
- while (ticketsCount> 0){
- ticketsCount--;// 如果还有票 就卖掉一张
- System.out.println(Thread.currentThread().getName()+"卖了 1 张票, 剩余票数为:"+ticketsCount);
- }
- }
- }
- public class TicketsRunnable {
- public static void main(String[] args){
- MyThreadRunnable mt = new MyThreadRunnable();
- // 创建三个线程 来模拟 三个售票窗口
- Thread th1 = new Thread(mt,"窗口 1");
- Thread th2 = new Thread(mt,"窗口 2");
- Thread th3 = new Thread(mt,"窗口 3");
- // 启动这三个线程 也即是三个窗口开始卖票
- th1.start();
- th2.start();
- th3.start();
- // 线程生命周期 创建 - 就绪 - 阻塞 - 运行状态 - 终止状态
- }
- }
4. 生命周期流程图
image.PNG
知识细节:
当多线程创建 后执行 start 就会进入就绪状态 不一定马上执行 主要看有没有 CPU 资源
如果有马上执行 就会进入运行状态 运行完成 就会进入终止状态
如果调用 sleep 就会进入阻塞状态 让出 CPU 资源 让其他线程执行 如果 sleep 阻塞结束 该线程就会进入就绪状态 重新获取 CPU 资源
来源: http://www.jianshu.com/p/1b3cab093dff