21xrx.com
2024-06-02 22:45:04 Sunday
登录
文章检索 我的文章 写文章
我学习Java中线程创建的两个方法
2023-06-11 07:34:47 深夜i     --     --
Java 线程 代码

作为一名Java初学者,学习多线程编程是不可避免的。在Java中创建线程有两种方法,分别是继承Thread类和实现Runnable接口。在本文中,我将介绍这两种方法并给出代码示例。

1. 继承Thread类

使用继承Thread类创建线程非常简单,只需要定义一个继承Thread类的子类,然后重写run()方法即可。具体代码如下:


public class MyThread extends Thread {

  @Override

  public void run() {

    System.out.println("Hello from MyThread!");

  }

}

public class Main {

  public static void main(String[] args) {

    MyThread thread = new MyThread();

    thread.start();

  }

}

2. 实现Runnable接口

使用实现Runnable接口创建线程比较灵活,因为可以实现多个接口。具体代码如下:


public class MyRunnable implements Runnable {

  @Override

  public void run() {

    System.out.println("Hello from MyRunnable!");

  }

}

public class Main {

  public static void main(String[] args) {

    MyRunnable runnable = new MyRunnable();

    Thread thread = new Thread(runnable);

    thread.start();

  }

}

总结:

在Java中创建线程有两种方法,继承Thread类和实现Runnable接口。两种方法都非常简单易懂,根据需要选择即可。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复