21xrx.com
2025-04-09 23:55:45 Wednesday
文章检索 我的文章 写文章
我是一名Java开发者
2023-06-15 19:16:27 深夜i     5     0

我是一名Java开发者,今天我想跟大家分享Java中线程的创建方式。在Java中,有三种方式可以创建线程:继承Thread类、实现Runnable接口、实现Callable接口。

继承Thread类

我们可以创建一个新的类来继承Thread类,并重写run()方法。run()方法中的代码将在新线程中执行。下面是一个例子:

class MyThread extends Thread {
  public void run() {
    System.out.println("This code is running in a new thread");
  }
}
public class Main {
  public static void main(String[] args) {
    MyThread thread = new MyThread();
    thread.start();
  }
}

在上面的例子中,我们创建了一个MyThread类,继承Thread类。在该类中重写了run()方法,并在该方法中输出了一段文字。然后我们在main()方法中创建了一个MyThread对象并调用它的start()方法来启动新线程。

实现Runnable接口

我们可以创建一个新的类来实现Runnable接口,并实现它的run()方法。下面是一个例子:

class MyRunnable implements Runnable {
  public void run() {
    System.out.println("This code is running in a new thread");
  }
}
public class Main {
  public static void main(String[] args) {
    Thread thread = new Thread(new MyRunnable());
    thread.start();
  }
}

在上面的例子中,我们创建了一个MyRunnable类,实现Runnable接口,并实现了它的run()方法。然后我们在main()方法中创建了一个Thread对象,并传递一个MyRunnable对象作为构造函数的参数。最后我们调用该Thread对象的start()方法来启动新线程。

实现Callable接口

和实现Runnable接口类似,我们也可以实现Callable接口,并实现它的call()方法。但是和Runnable不同,call()方法可以返回一个结果。下面是一个例子:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable
  {
 
  public String call()
    return "This code is running in a new thread";
  
}
public class Main {
  public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future
  future = executorService.submit(new MyCallable());
 
    System.out.println(future.get());
    executorService.shutdown();
  }
}

在上面的例子中,我们创建了一个MyCallable类,实现Callable接口,并实现了它的call()方法。并且我们使用了ExecutorService来管理线程池,并提交了我们的MyCallable对象来运行它的call()方法。由于call()方法返回了一个String类型的结果,我们可以通过Future对象的get()方法来获得它。最后我们关闭了线程池。

综上所述,Java中有三种方式可以创建线程:继承Thread类、实现Runnable接口、实现Callable接口。不同的方式适用于不同的场景,我们在使用时需要根据实际情况做出选择。

  
  

评论区