Skip to content

创建和使用一个线程

  • 使用Thread类创建线程
java
public class ThreadDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> System.out.println("Hello from a thread!"));
        thread.start();
    }
}
  • 使用Runnable接口创建线程
java
public class RunnableDemo {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println("Hello from a thread!");
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
  • 使用FutureTask类创建线程
java
public class FutureTaskDemo {
    public static void main(String[] args) {
        FutureTask<String> futureTask = new FutureTask<>(() -> "Hello from a thread!");
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 使用Callable接口创建线程
java
public class CallableDemo {
    public static void main(String[] args) {
        Callable<String> callable = () -> "Hello from a thread!";
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(callable);
        try {
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }
}