Java中的多线程
多线程是一种Java功能,它允许同时执行程序的两个或多个部分,以最大限度地利用 CPU。这种程序的每一部分都称为一个线程。因此,线程是进程中的轻量级进程。
可以使用两种机制创建线程:
- 扩展线程类
- 实现可运行接口
通过扩展 Thread 类创建线程
我们创建一个扩展Java.lang.Thread类的类。此类覆盖 Thread 类中可用的 run() 方法。线程在 run() 方法中开始其生命。我们创建新类的对象并调用 start() 方法来开始执行线程。 Start() 调用 Thread 对象的 run() 方法。
Java
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Java
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
输出
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
通过实现 Runnable 接口创建线程
我们创建了一个实现Java.lang.Runnable 接口并覆盖 run() 方法的新类。然后我们实例化一个 Thread 对象并在这个对象上调用 start() 方法。
Java
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
输出
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
线程类与可运行接口
- 如果我们扩展 Thread 类,我们的类不能扩展任何其他类,因为Java不支持多重继承。但是,如果我们实现 Runnable 接口,我们的类仍然可以扩展其他基类。
- 我们可以通过扩展 Thread 类来实现线程的基本功能,因为它提供了一些在 Runnable 接口中不可用的内置方法,如 yield()、interrupt() 等。
- 使用 runnable 将为您提供一个可以在多个线程之间共享的对象。