1.继承Thread
package com.company;
//继承Thread,重写run方法,调用start()
public class 创建线程1 extends Thread{
@Override
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("另一个线程执行中"+i);
}
}
public static void main(String[] args) {
创建线程1 a = new 创建线程1();
a.start();
for (int i = 0; i < 2000; i++) {
System.out.println("主线程执行中"+i);
}
}
}
2.实现Runnable接口
package com.company;
//实现runnable接口,重写run方法,调用start()
public class 创建线程2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("另一个线程执行中"+i);
}
}
public static void main(String[] args) {
创建线程2 a = new 创建线程2();
new Thread(a).start();
for (int i = 0; i < 2000; i++) {
System.out.println("主线程执行中" + i);
}
}
}
3.实现Callable接口
package com.company;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.concurrent.*;
//实现Callable
/*好处:
* 1.可以自定义返回值
* 2.可以抛出异常
* */
public class 创建线程3 implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"输出了"+i);
}
return true;
}
public static void main(String[] args) throws Exception {
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(1);
//提交执行
Future<Boolean> r1 = ser.submit(new 创建线程3());
//获取结果
boolean rs1 = r1.get();
System.out.println(rs1);
//关闭服务
ser.shutdown();
}
}