Java中的多线程函数及其使用方法
Java是一种面向对象的编程语言,具有多线程功能。Java中的多线程是在同一个程序中同时执行多个线程,从而可以提高程序的运行效率。Java中的多线程函数有很多,使用方法也有所不同。下面详细介绍Java中的多线程函数及其使用方法。
1. Thread
Thread是Java中实现多线程的基本类,在Java中实现多线程必须继承Thread类,并重写run()方法。在主程序中创建线程对象,然后调用start()方法启动线程,run()方法将在新线程中自动执行。示例代码如下:
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
2. Runnable
Runnable是另一种实现多线程的方式,它是一个可以被执行的类,不同于Thread,它没有自己的线程执行体。在Runnable中需要实现run()方法,然后在主程序中创建线程对象,并以Runnable实例为参数,调用start()方法启动线程。示例代码如下:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
3. join
join方法可以等待一个线程执行完后再继续执行主线程,它的作用是等待该线程执行完毕,直到该线程结束才执行其他线程。join方法必须在start方法调用之后,才能调用。示例代码如下:
public class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Thread is running...");
}
}
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join();
System.out.println("Main thread is running...");
}
}
4. yield
yield方法能使线程暂停,让其他线程有机会执行,但它不会释放锁。yield方法被调用后,该线程仅有可能重新进入可执行状态,而不是进入运行状态,重新进入运行状态还要取决于具体的线程调度器。示例代码如下:
public class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Thread is running...");
Thread.yield();
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
5. sleep
sleep方法是让当前线程进入睡眠状态,休眠指定时间。当线程睡眠时,它不会占用CPU资源,其他线程有机会执行。sleep方法不能释放锁。当休眠时间到达后,线程会重新进入可执行状态。示例代码如下:
public class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000); //休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
6. interrupt
interrupt方法可以中断线程的执行,触发InterruptedException异常。在线程中使用isInterrupted方法可以判断线程是否被中断。示例代码如下:
public class MyThread extends Thread {
public void run() {
while(!isInterrupted()) {
System.out.println("Thread is running...");
}
}
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
Thread.sleep(1000);
t.interrupt();
}
}
7. setPriority
setPriority方法可以设置线程的优先级,优先级值范围为1~10,1为最低优先级,10为最高优先级。优先级高的线程具有更高的执行权。示例代码如下:
public class MyThread extends Thread {
public void run() {
System.out.println("Current thread priority is " + getPriority());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
总之,Java中的多线程函数有很多,使用方法也有所不同。以上只是介绍了Java中的几种多线程函数及其使用方法,希望能对读者有所帮助。
