在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());
}
}
创建并启动线程:
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
synchronized关键字或者Lock接口来实现线程同步。wait()、notify()和notifyAll()方法来实现线程间的通信。下面是一个完整的示例代码,展示了如何使用Runnable接口实现多线程:
class MyRunnable implements Runnable {
private int count = 0;
@Override
public void run() {
while (count < 5) {
synchronized (this) {
System.out.println("线程 " + Thread.currentThread().getName() + " 计数: " + count);
count++;
try {
Thread.sleep(1000); // 让线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable, "线程1");
Thread thread2 = new Thread(runnable, "线程2");
thread1.start();
thread2.start();
}
}
在这个示例中,两个线程共享同一个MyRunnable实例,并且通过synchronized关键字确保对count变量的访问是线程安全的。每个线程会打印计数器的值,并让线程休眠1秒。