掌握线程的创建与终止方法实验
时间: 2023-12-03 09:43:33 浏览: 25
线程的创建与终止方法可以使用Java中的Thread类来实现。
### 线程的创建方法
1. 继承Thread类并重写run()方法,然后调用start()方法启动线程。
```java
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Hello, I am a new thread!");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
```
2. 实现Runnable接口并重写run()方法,然后创建Thread对象并调用start()方法启动线程。
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello, I am a new thread!");
}
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
```
### 线程的终止方法
1. 使用标志位终止线程。在run()方法中通过判断标志位来决定是否终止线程。
```java
public class MyThread extends Thread {
private volatile boolean flag = true;
public void stopThread() {
flag = false;
}
@Override
public void run() {
while (flag) {
// do something
}
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
// 等待一段时间后终止线程
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopThread();
}
```
2. 使用interrupt()方法终止线程。在run()方法中通过判断线程是否被中断来决定是否终止线程。
```java
public class MyThread extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// do something
}
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
// 等待一段时间后中断线程
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
```