微信

使用微信服务,更方便

职友集>Java面试题 > java创建线程示例代码?

java创建线程示例代码?

2015-08-15 06:30:01 阅读( 42 )

2128人 收藏本页

标签: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();
}
}

下一篇:java Servlet实现跳转到另一个url

上一篇:java打印杨辉三角

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题