Java创建新线程(实现Runnable接口)
Java中创建一个新线程主要有两种方法,重写run方法和实现Runnable接口。
这里展示了实现Runnable接口来创建一个新线程。
先声明一个实现了Runnable接口的类MyRunnable,然后在类中实现了run方法。把这个线程要做的事写在run方法中,例如每秒钟打印一次时间。 MyRunnable.java
import java.util.Date; import static java.lang.Thread.sleep; public class MyRunnable implements Runnable { @Override public void run() { while (true) { System.out.println("Thread 1 " + new Date()); try { sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
然后在主方法中实例化一个对象,在创建Thread时作为参数传递,并启动。
import java.util.Date; import static java.lang.Thread.sleep; public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } }
也可以直接在匿名类中实现run方法,创建起来更方便。
import java.util.Date; import static java.lang.Thread.sleep; public class Main { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { while (true) { System.out.println("Thread 2 " + new Date()); try { sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }).start(); } }
下一篇:
java获取当前年月日时分秒等