Java里面实现多线程,有2个方法
1 继承 Thread类
class MyThread extends Thread {
public void run() {
// 这里写上线程的内容
}
public static void main(String[] args) {
// 使用这个方法启动一个线程
new MyThread().start();
}
}
2 实现 Runnable接口
class MyThread implements Runnable{
public void run() {
// 这里写上线程的内容
}
public static void main(String[] args) {
// 使用这个方法启动一个线程
new Thread(new MyThread()).start();
}
}
一般鼓励使用第二种方法,因为Java里面只允许单一继承,但允许实现多个接口。第二个方法更加灵活
1 继承 Thread类
class MyThread extends Thread {
public void run() {
// 这里写上线程的内容
}
public static void main(String[] args) {
// 使用这个方法启动一个线程
new MyThread().start();
}
}
2 实现 Runnable接口
class MyThread implements Runnable{
public void run() {
// 这里写上线程的内容
}
public static void main(String[] args) {
// 使用这个方法启动一个线程
new Thread(new MyThread()).start();
}
}
一般鼓励使用第二种方法,因为Java里面只允许单一继承,但允许实现多个接口。第二个方法更加灵活
本文介绍了Java中实现多线程的两种主要方法:通过继承Thread类和实现Runnable接口。这两种方式各有特点,其中推荐使用实现Runnable接口的方式以提高程序的灵活性。

被折叠的 条评论
为什么被折叠?



