方式一: 继承Thread类
public class thread {
public static void main(String[] args) {
thread1 thread1=new thread1();
Thread thread=new Thread(thread1);
thread.start();
}
}
class thread1 extends Thread{
@Override
public void run() {
for (int i = 0; i <3 ; i++) {
System.out.println("thread1:"+currentThread().getName());
}
}
}
方式二: 实现Runnable接口
public class thread {
public static void main(String[] args) {
thread2 thread2=new thread2();
Thread thread=new Thread(thread2);
thread.start();
}
}
class thread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <3 ; i++) {
System.out.println("thread2:"+Thread.currentThread().getName());
}
}
}
方式三: 实现Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class thread {
public static void main(String[] args) throws Exception {
thread3 thread3=new thread3();
FutureTask futureTask=new FutureTask(thread3);
Thread thread=new Thread(futureTask);
thread.start();
}
}
class thread3 implements Callable{
@Override
public Object call() throws Exception {
for (int i = 0; i <3 ; i++) {
System.out.println("thread3:"+Thread.currentThread().getName());
}
return true;
}
}
方式四: 线程池
import java.util.concurrent.*;
public class thread {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 2L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 0; i < 3; i++) {
threadPoolExecutor.execute(() -> {
System.out.println("thread4:" + Thread.currentThread().getName());
});
}
}
catch (Exception e){
e.printStackTrace();
}finally {
threadPoolExecutor.shutdown();
}
}
}
线程池的具体原理可以看我的线程池那片文章。