多线程是指在一个程序中同时运行多个线程,每个线程执行不同的任务。多线程可以提高程序的并发性和响应性,充分利用CPU资源。
以下是一个简单的Java示例,展示如何实现两个类同时运行:
public class MultiThreadExample {
public static void main(String[] args) {
// 创建两个线程
Thread thread1 = new Thread(new Task1());
Thread thread2 = new Thread(new Task2());
// 启动线程
thread1.start();
thread2.start();
}
}
class Task1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Task1 - " + i);
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Task2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Task2 - " + i);
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
synchronized
关键字或Lock
接口。public class SharedResource {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class DeadlockExample {
private static final Object resource1 = new Object();
private static final Object resource2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread1: Holding resource 1...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread1: Waiting for resource 2...");
synchronized (resource2) {
System.out.println("Thread1: Holding resource 1 & 2...");
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (resource2) {
System.out.println("Thread2: Holding resource 2...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread2: Waiting for resource 1...");
synchronized (resource1) {
System.out.println("Thread2: Holding resource 1 & 2...");
}
}
});
thread1.start();
thread2.start();
}
}
通过以上内容,您可以了解多线程的基础概念、优势、类型、应用场景以及常见问题的解决方法。希望这些信息对您有所帮助。
领取专属 10元无门槛券
手把手带您无忧上云