Java中如何实现多线程及其相关函数
发布时间:2023-07-27 19:19:14
Java中实现多线程有两种方式:继承Thread类和实现Runnable接口。
1. 继承Thread类:
首先,创建一个继承自Thread类的子类,并重写run()方法,用来定义线程的执行逻辑。然后,创建该子类的实例,并调用start()方法启动线程。
示例代码如下:
class MyThread extends Thread {
public void run() {
// 线程执行逻辑
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2. 实现Runnable接口:
创建一个实现了Runnable接口的类,并实现其中的run()方法。然后,创建该类的实例,并传递给Thread类的构造函数中,最后调用Thread的start()方法启动线程。
示例代码如下:
class MyRunnable implements Runnable {
public void run() {
// 线程执行逻辑
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
Java中线程相关的常用函数有:
1. sleep():使当前线程从运行状态进入阻塞状态,指定的时间后再进入就绪状态。示例代码如下:
try {
Thread.sleep(1000); // 阻塞当前线程1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
2. join():在一个线程中调用其他线程的join()方法,该线程就会等待其他线程执行完毕后再继续执行。示例代码如下:
Thread thread1 = new Thread(() -> {
System.out.println("Thread1 is running");
});
Thread thread2 = new Thread(() -> {
try {
thread1.join(); // 等待thread1执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2 is running");
});
thread1.start();
thread2.start();
3. yield():暂停当前正在执行的线程对象,并执行其他线程。示例代码如下:
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread1 is running");
Thread.yield(); // 暂停当前线程,执行其他线程
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread2 is running");
Thread.yield(); // 暂停当前线程,执行其他线程
}
});
thread1.start();
thread2.start();
}
}
4. interrupt():中断线程的执行。示例代码如下:
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行逻辑
}
});
thread.start();
thread.interrupt(); // 中断线程
以上是Java中实现多线程及其相关函数的简单介绍,还有其他更复杂的线程操作可以根据需要进行学习和使用。
