public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("This is my customized thread.");
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
2、实现Runnable接口
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("This is my customized thread.");
}
public static void main(String[] args) {
RunnableDemo runnableDemo = new RunnableDemo();
Thread thread = new Thread(runnableDemo);
thread.start();
}
}
3、实现Callable接口
public class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("当前线程:" + Thread.currentThread().getName());
return "Hello, this is response value.";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableDemo callableDemo = new CallableDemo();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(callableDemo);
// Future.get()是一个阻塞方法,会阻塞主线程
System.out.println(Thread.currentThread().getName() + "########" + future.get());
}
}
4、通过ThreadPoolExecutor线程池获取线程
public class ThreadPoolDemo implements Runnable {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
//ExecutorService executorService = Executors.newSingleThreadExecutor();
//ExecutorService executorService = Executors.newCachedThreadPool();
//ExecutorService executorService = Executors.newScheduledThreadPool(2);
for (int i = 0; i < 10; i ++) {
executorService.execute(new ThreadPoolDemo());
}
executorService.shutdown();
}
@Override
public void run() {
try {
System.out.println("当前运行的线程是" + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}