Java多线程编程中常用函数的介绍和示例
发布时间:2023-11-26 20:31:08
在Java多线程编程中,有一些常用的函数和方法可以帮助我们实现多线程的控制和管理。下面是一些常用函数的介绍和示例。
1. sleep函数
sleep函数用于使当前线程进入休眠状态,指定的时间过后线程会被自动唤醒。它的函数签名为:public static void sleep(long millis),其中millis为休眠时间,单位为毫秒。
示例:
public class SleepExample {
public static void main(String[] args) {
try {
System.out.println("Thread sleep 5 seconds");
Thread.sleep(5000); // 休眠5秒
System.out.println("Thread wake up");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2. join函数
join函数用于使一个线程等待另一个线程执行完毕后再继续执行。它的函数签名为:public final void join()。
示例:
public class JoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
thread1.join(); // 等待thread1执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
}
}
});
thread1.start();
thread2.start();
}
}
3. yield函数
yield函数用于使当前线程让出CPU执行权,让其他具有相同优先级的线程有机会执行。它的函数签名为:public static native void yield()。
示例:
public class YieldExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
Thread.yield(); // 当前线程让出CPU执行权
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
Thread.yield(); // 当前线程让出CPU执行权
}
}
});
thread1.start();
thread2.start();
}
}
4. interrupt函数
interrupt函数用于中断线程的执行。它的函数签名为:public void interrupt()。
示例:
public class InterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重设中断状态
}
}
}
});
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt(); // 中断线程执行
}
}
以上介绍了Java多线程编程中一些常用的函数和方法,通过使用这些函数和方法,我们可以更好地控制和管理多线程的执行。希望以上内容对您有帮助。
