1.Thread类
继承Thread类,重写run()方法
public class ThreadDemo {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println("MyThread");
}
}
注意:调用了start方法以后,线程才算启动,虚拟机会先为我们创建一个线程,等到这个线程第一次得到时间片时再调用run()方法,不可多次调用start()方法,否则会抛出异常java.lang.IllegalThreadStateException
2.实现Runnable接口
public class ThreadDemo2 {
public static void main(String[] args) {
Thread thread = new Thread(new MyThread2());
thread.start();
new Thread(()->{
System.out.println("Java8匿名内部类");
},"aaa").start();
}
}
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread");
}
}
3.实现Callable接口
public class Task implements Callable {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 10;
}
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
Task task = new Task();
Future result = executorService.submit(task);
System.out.println(result.get(1, TimeUnit.SECONDS));
}
}