1.继承Thread类
class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("继承Thread类");
}
}
2.实现Runnable方法
class ThreadDemo2 implements Runnable {
@Override
public void run() {
System.out.println("实现runnable方法");
}
}
3.java8显示创建线程
new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("线程2");
}
}).start();
4.使用线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
threadPoolExecutor.execute(()->{
for (int i = 0; i < 100; i++) {
System.out.println("线程1");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});