Java多线程编程详细解释
简介
Java中的多线程编程是一种同时执行多个线程的方式,它可以提高程序性能和资源利用率。本文将详细介绍Java多线程编程,让你能够了解创建和管理线程的方法,以及如何避免线程安全问题。
创建线程的方法
Java中有两种创建线程的方法:
方法一:继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running...");
}
}
public class TestThread {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
方法二:实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("MyRunnable is running...");
}
}
public class TestRunnable {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
线程状态
Java中的线程有6种状态:新建状态(New)、就绪状态(Runnable)、阻塞状态(Blocked)、等待状态(Waiting)、计时等待状态(Timed Waiting)和终止状态(Terminated)。
public class TestThreadState {
public static void main(String[] args) {
Thread t = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState()); // TIMED_WAITING
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState()); // TERMINATED
}
}
线程同步
多个线程之间可能会访问同一个资源,为了避免线程安全问题,我们需要对访问该资源的代码进行同步。Java中的同步机制有以下两种:
方法一:synchronized关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized void decrement() {
count--;
}
public synchronized int getCount() {
return count;
}
}
public class TestSynchronized {
public static void main(String[] args) {
Counter counter = new Counter();
for (int i = 0; i < 1000; i++) {
new Thread(() -> counter.increment()).start();
new Thread(() -> counter.decrement()).start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.getCount()); // 0
}
}
方法二:Lock接口
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public void decrement() {
lock.lock();
try {
count--;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
public class TestLock {
public static void main(String[] args) {
Counter counter = new Counter();
for (int i = 0; i < 1000; i++) {
new Thread(() -> counter.increment()).start();
new Thread(() -> counter.decrement()).start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.getCount()); // 0
}
}
示例一:生产者消费者问题
class Producer implements Runnable {
private Queue<Integer> queue;
private int max;
public Producer(Queue<Integer> queue, int max) {
this.queue = queue;
this.max = max;
}
public void run() {
int i = 0;
while (true) {
synchronized (queue) {
while (queue.size() == max) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(i);
System.out.println("Produced " + i);
i++;
queue.notifyAll();
}
}
}
}
class Consumer implements Runnable {
private Queue<Integer> queue;
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = queue.poll();
System.out.println("Consumed " + num);
queue.notifyAll();
}
}
}
}
public class TestProducerConsumer {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
Producer p = new Producer(queue, 5);
Consumer c = new Consumer(queue);
new Thread(p).start();
new Thread(c).start();
}
}
示例二:死锁问题
public class TestDeadlock {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (lock2) {
System.out.println("Thread 1: Holding lock 1 and lock 2...");
}
}
}).start();
new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (lock1) {
System.out.println("Thread 2: Holding lock 1 and lock 2...");
}
}
}).start();
}
}
总结
Java多线程编程是Java程序的重要组成部分。通过掌握线程的基本知识,如创建和管理线程、线程状态、线程同步等,可以优化程序性能、提高资源利用率,并解决线程安全问题。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java多线程编程详细解释 - Python技术站