Java并发编程第一弹
发布人:shili8
发布时间:2024-11-09 05:53
阅读次数:0
**Java 并发编程第一弹**
在 Java 中,多线程编程是非常重要的概念。它允许我们同时执行多个任务,从而提高程序的性能和效率。在本文中,我们将介绍 Java 并发编程的基本概念、常见问题以及一些实用的示例代码。
**1. 线程的基本概念**
在 Java 中,线程是程序执行的一个单元。每个线程都有自己的栈空间和局部变量。线程可以共享同一个堆空间,但每个线程都有自己的寄存器和栈空间。
**2. 线程的状态**
Java 中的线程有以下几种状态:
* **新建(New):** 当线程被创建时,它处于新建状态。
* **就绪(Runnable):** 当线程准备好执行时,它处于就绪状态。
* **运行(Running):** 当线程正在执行时,它处于运行状态。
* **阻塞(Blocked):** 当线程等待某个资源或事件时,它处于阻塞状态。
* **死亡(Dead):** 当线程完成执行时,它处于死亡状态。
**3. 线程的创建**
在 Java 中,线程可以通过以下几种方式创建:
* **继承Thread类:** 可以直接继承 Thread 类,并重写 run() 方法。
* **实现Runnable接口:** 可以实现 Runnable 接口,并重写 run() 方法。
示例代码:
java// 继承Thread类class MyThread extends Thread {
@Override public void run() {
System.out.println("线程执行了!");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程 }
}
java// 实现Runnable接口class MyRunnable implements Runnable {
@Override public void run() {
System.out.println("线程执行了!");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // 启动线程 }
}
**4. 线程的同步**
在 Java 中,线程之间共享同一个堆空间,但每个线程都有自己的寄存器和栈空间。为了避免多线程访问共享资源时的冲突,我们需要使用同步机制。
示例代码:
javaclass Counter {
private int count =0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i =0; i < 10000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i =0; i < 10000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(counter.getCount()); // 输出20000 }
}
**5. 线程的通信**
在 Java 中,线程之间可以通过以下几种方式进行通信:
* **wait()和notify()方法:** 可以使用 wait() 方法让线程等待某个事件,而 notify() 方法可以唤醒等待的线程。
* **Lock接口:** 可以使用 Lock 接口来实现更高级别的同步机制。
示例代码:
javaclass Counter {
private int count =0;
private final Object lock = new Object();
public void increment() {
synchronized (lock) {
count++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("线程执行了!");
}
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i =0; i < 10000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i =0; i < 10000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(counter.getCount()); // 输出20000 }
}
**6. 线程池**
在 Java 中,线程池可以帮助我们管理多个线程的生命周期。它可以重用已经存在的线程,从而避免创建和销毁线程带来的性能开销。
示例代码:
javaimport java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i =0; i < 10000; i++) {
final int index = i;
executor.submit(() -> {
System.out.println("线程执行了!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(index);
});
}
executor.shutdown();
}
}
**7. 线程的优先级**
在 Java 中,线程可以设置优先级,从而影响其执行顺序。
示例代码:
javaclass MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new MyThread("线程1");
Thread thread2 = new MyThread("线程2");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
**8. 线程的中断**
在 Java 中,线程可以通过中断来结束其执行。
示例代码:
javaclass MyThread extends Thread {
@Override public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread("线程");
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
thread.interrupt();
}
}
**9. 线程的状态**
在 Java 中,线程可以通过 getState() 方法获取其当前状态。
示例代码:
javaclass MyThread extends Thread {
@Override public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread("线程");
thread.start();
System.out.println(thread.getState()); // 输出 NEW try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(thread.getState()); // 输出 RUNNABLE }
}
**10. 线程的生命周期**
在 Java 中,线程可以通过以下几种方式结束其执行:
* **正常结束:** 当线程完成其任务时,它会自动结束。
* **异常结束:** 当线程遇到异常时,它会被终止。
* **中断结束:** 当线程被中断时,它会被终止。
示例代码:
javaclass MyThread extends Thread {
@Override public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread("线程");
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(thread.getState()); // 输出 RUNNABLE thread.join(); // 等待线

