java怎么创建多线程
时间: 2023-10-13 08:14:24 浏览: 46
Java中创建多线程的方法有两种:
1. 继承Thread类并重写run()方法
```java
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
}
}
// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();
```
2. 实现Runnable接口并重写run()方法
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
// 创建并启动线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
```
在Java中,启动线程需要调用start()方法,而不是run()方法。start()方法会在新的线程中执行run()方法。
相关问题
java 创建多线程
以下是两种Java创建多线程的例子:
1. 继承Thread类创建多线程[^1]
java
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("使用继承Thread类创建多线程");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
2. 使用匿名内部类,实现Runnable接口[^2]
```java
public class Main {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("使用匿名内部类,实现Runnable接口");
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
```
Java 创建多线程代码
以下是 Java 中创建多线程的代码示例:
1. 继承 Thread 类:
```java
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
```
2. 实现 Runnable 接口:
```java
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable();
MyRunnable r2 = new MyRunnable();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
```
3. 使用匿名内部类:
```java
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
// 线程执行的代码
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
// 线程执行的代码
}
});
t1.start();
t2.start();
}
}
```