在Ubuntu下使用Java实现多线程,主要有两种方法:继承Thread
类和实现Runnable
接口。下面分别介绍这两种方法的实现步骤。
Thread
类创建一个继承自Thread
类的子类:
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行: " + Thread.currentThread().getName());
}
}
创建并启动线程:
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
Runnable
接口创建一个实现Runnable
接口的类:
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行: " + Thread.currentThread().getName());
}
}
创建一个Thread
对象,并将Runnable
对象作为参数传递给它:
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
synchronized
关键字来保证同一时间只有一个线程可以访问共享资源。wait()
、notify()
和notifyAll()
方法来实现线程间的通信。ExecutorService
来管理线程池,提高性能和资源利用率。下面是一个完整的示例代码,展示了如何使用Runnable
接口实现多线程:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程 " + Thread.currentThread().getName() + " 正在运行: " + i);
try {
Thread.sleep(1000); // 模拟线程执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "线程1");
Thread thread2 = new Thread(myRunnable, "线程2");
thread1.start();
thread2.start();
}
}
运行上述代码,你会看到两个线程交替执行,并且每个线程都会打印出自己的名称和循环计数。