java创建线程示例代码,java线程示例代码,在java中有两种方法可
分享于 点击 28221 次 点评:113
java创建线程示例代码,java线程示例代码,在java中有两种方法可
在java中有两种方法可以创建线程,一种方法是从Thread类继承,实现Thread类的run方法,另一种方式是实现Runnable接口,然后将Runnable的对象作为参数给Thread实例。
如下是两种方法的实现代码示例:
从Thread类继承实现多线程:
public class MyThread extends Thread { /** * This method is executed when the start() method is called on the thread * so here you will put the 'thread code'. */ public void run() { System.out.println("Thread executed!"); } /** * @param args the command line arguments */ public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); }}
通过实现Runnable接口实现多线程:
public class MyRunnable implements Runnable { /** * As in the previous example this method is executed * when the start() method is called on the thread * so here you will put the 'thread code'. */ public void run() { System.out.println("Thread executed!"); } /** * @param args the command line arguments */ public static void main(String[] args) { //create a Thread object and pass it an object of type Runnable Thread thread = new Thread(new MyRunnable()); thread.start(); }}
用户点评