且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java多线程初探

更新时间:2022-08-22 10:59:43

多线程

单线程的程序只有一个顺序执行流。多个顺序流之间互不干扰。

多线程的创建

  1. 定义Thread类的子类,重写该类的run()方法。
  2. 创建Thread子类的实例。
  3. 调用线程对象的start()方法来启动多线程。
package ch16;

/**
 * Created by Jiqing on 2017/1/2.
 */
public class FirstThread extends Thread{
    private int i;
    // 重写run方法
    public void run() {
        for (;i<100;i++) {
            System.out.println(getName() + " run " + i); // 获取线程的名字
        }
    }

    public static void main(String[] args) {
        for(int i = 0;i<200;i++) {
            // 调用Thread的currentThread方法获取当前线程
            System.out.println(Thread.currentThread().getName() +" main "+ i);
            if (i == 20) {
                // 创建并启动第一个线程
                new FirstThread().start();
                // 创建并启动第二个线程
                new FirstThread().start();
            }
        }
    }
}

案例中当执行到20的时候,启动了线程。此时,三个进程轮流执行。main,thread0,thread1交替进行。



本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6243467.html,如需转载请自行联系原作者