首先需要理解清楚程序、进程、线程
程序:即静态的代码块;
进程:执行中的进程;
线程:进程的进一部细分,程序的一条执行路径;
第一种 创建一个类继承Thread,并重写run()方法
/第一种方法:创建一个继承Thread的子类
class SubThread extends Thread{
//重写run()
public void run(){
//输出1-100
for (int i = 1; i <=100 ; i++) {
System.out.println(i);
}
}
}
public class TestThread{
public static void main(String[] args) {
//第一种方式:创建一个子类对象
SubThread subThread = new SubThread();
SubThread subThread1 = new SubThread();
//调用线程的start(),启动此线程,调用相应的run()
subThread.start();
subThread1.start();
for (int i = 1; i <=100 ; i++) {
System.out.println(i);
}
System.out.println( subThread1.isAlive());
}
}
第二种:创建一个类实现Runnable接口,并重写run()方法
//第二种方式:实现Runnable接口,重写run()
class SubThread2 implements Runnable{
@Override
public void run() {
for (int i = 1; i <=100 ; i++) {
if (i%2==0){
System.out.println(i);
}
}
}
}
public class TestThread{
public static void main(String[] args) {
//第二种方式:创建一个接口实现类的对象
SubThread2 subThread2 = new SubThread2();
//将该对象作为形参传递给Thread类的构造器,创建Thread类的对象,此对象即为一个线程
Thread thread = new Thread(subThread2);
//启动线程,执行Thread对象生成时构造器形参的对象的run()
thread.start();
}
}
第三种:
使用ExecutorService、Callable、Future实现又返回结果的多线程