详解Java线程的创建及休眠
线程的概念
Java 线程是一条执行路径,每个线程都是独立的,它们之间不会相互影响,每个线程有自己的计数器、栈和程序计数器。线程是轻量级的,因为创建和销毁线程所需的时间和资源相对较少。
Java线程的创建
Java 线程是通过 Thread 类来实现的。创建线程的方式有两种,分别是:
继承 Thread 类
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
MyThread thread = new MyThread();
thread.start();
实现 Runnable 接口
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running.");
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
线程的休眠
线程休眠是指暂停当前线程的执行,让出 CPU 时间片,让其他线程或进程得到执行机会。Java 中线程的休眠由 Thread 类的 sleep() 方法实现。
try {
// 休眠3秒
Thread.sleep(3000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
示例说明
示例1:继承 Thread 类
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
System.out.println(name + " is running.");
try {
// 休眠5秒
Thread.sleep(5000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(name + " is complete.");
}
}
// 创建两个线程
MyThread thread1 = new MyThread("Thread1");
MyThread thread2 = new MyThread("Thread2");
// 启动线程
thread1.start();
thread2.start();
此示例中,我们创建了两个继承了 Thread 类的线程,分别为 thread1 和 thread2,它们执行时会打印出自己的名称,并且在执行过程中休眠了 5 秒钟。输出结果可能是:
Thread1 is running.
Thread2 is running.
Thread1 is complete.
Thread2 is complete.
示例2:实现 Runnable 接口
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + " is running.");
try {
// 休眠5秒
Thread.sleep(5000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(name + " is complete.");
}
}
// 创建两个线程
MyRunnable runnable1 = new MyRunnable("Thread1");
MyRunnable runnable2 = new MyRunnable("Thread2");
// 创建线程对象
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
// 启动线程
thread1.start();
thread2.start();
此示例中,我们创建了两个实现了 Runnable 接口的线程,分别为 runnable1 和 runnable2,它们执行时会打印出自己的名称,并且在执行过程中休眠了 5 秒钟。输出结果可能是:
Thread1 is running.
Thread2 is running.
Thread1 is complete.
Thread2 is complete.
总结
Java 的线程机制可以进一步优化程序的性能。线程的创建分两种方式:继承 Thread 类和实现 Runnable 接口。线程的休眠可以通过 sleep() 方法实现,让出 CPU 时间片,让其他线程或进程得到执行机会。在多线程编程中,线程的协作和同步非常重要,需要注意线程的安全问题。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解Java线程的创建及休眠 - Python技术站