java线程的创建有两种方式,这里我们通过简单的实例来学习一下。
java中多线程的创建
一、通过继承Thread类来创建多线程
public class HelloThread extends Thread { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); System.out.println("Hello from a thread!"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { HelloThread helloThread = new HelloThread(); helloThread.start(); System.out.println("In main thread."); } }
运行的结果如下:
In main thread. Hello from a thread!
二、通过实现Runnable接口来创建多线程
public class HelloRunnable implements Runnable { @Override public void run() { try { System.out.println("Hello from a thread!"); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Thread thread = new Thread(new HelloRunnable()); thread.start(); System.out.println("In main method."); } }
运行的结果如下:
In main method. Hello from a thread!
友情链接
时间: 2024-10-25 08:21:12