.请说明怎样让一段代码在新线程中运行Java
时间: 2024-02-25 16:55:42 浏览: 25
在Java中,要让一段代码在新线程中运行,可以使用Thread类或Runnable接口来创建新线程。
使用Thread类创建新线程的步骤如下:
1. 创建Thread对象,将需要在新线程中运行的代码放在Thread对象的run()方法中;
2. 调用Thread对象的start()方法,启动新线程。
以下是使用Thread类创建新线程的示例代码:
```java
public class NewThread extends Thread {
@Override
public void run() {
// 在新线程中运行的代码
System.out.println("新线程开始运行");
for (int i = 0; i < 10; i++) {
System.out.println("新线程输出:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("新线程结束运行");
}
public static void main(String[] args) {
// 创建新线程并启动
NewThread newThread = new NewThread();
newThread.start();
// 在主线程中运行的代码
System.out.println("主线程开始运行");
for (int i = 0; i < 5; i++) {
System.out.println("主线程输出:" + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线程结束运行");
}
}
```
上述代码中,首先创建了一个NewThread类继承自Thread类,并重写了run()方法,在其中编写需要在新线程中运行的代码。然后在main()方法中创建NewThread对象newThread,并调用start()方法启动新线程。
使用Runnable接口创建新线程的步骤如下:
1. 创建Runnable接口的实现类,将需要在新线程中运行的代码放在实现类的run()方法中;
2. 创建Thread对象,将Runnable实现类的实例对象作为参数传入Thread对象的构造方法中;
3. 调用Thread对象的start()方法,启动新线程。
以下是使用Runnable接口创建新线程的示例代码:
```java
public class NewThread implements Runnable {
@Override
public void run() {
// 在新线程中运行的代码
System.out.println("新线程开始运行");
for (int i = 0; i < 10; i++) {
System.out.println("新线程输出:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("新线程结束运行");
}
public static void main(String[] args) {
// 创建Runnable实现类的实例对象
NewThread newThread = new NewThread();
// 创建新线程并启动
Thread thread = new Thread(newThread);
thread.start();
// 在主线程中运行的代码
System.out.println("主线程开始运行");
for (int i = 0; i < 5; i++) {
System.out.println("主线程输出:" + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线程结束运行");
}
}
```
上述代码中,首先创建了一个NewThread类实现了Runnable接口,并实现了run()方法,在其中编写需要在新线程中运行的代码。然后在main()方法中创建NewThread对象newThread,并创建Thread对象thread,将newThread作为参数传入Thread对象的构造方法中,最后调用start()方法启动新线程。