您好,登录后才能下订单哦!
synchronized
关键字volatile
关键字ReentrantLock
ReadWriteLock
Condition
Semaphore
CountDownLatch
CyclicBarrier
Phaser
Exchanger
ForkJoinPool
CompletableFuture
ThreadLocal
Atomic
类BlockingQueue
ConcurrentHashMap
CopyOnWriteArrayList
StampedLock
LockSupport
Future
与FutureTask
并发是指多个任务在同一时间段内交替执行,从宏观上看,这些任务似乎是同时进行的。并发编程的目的是提高程序的执行效率,充分利用多核CPU的计算能力。
并发和并行是两个容易混淆的概念。并发是指多个任务在同一时间段内交替执行,而并行是指多个任务在同一时刻同时执行。并发可以通过时间片轮转的方式实现,而并行则需要多核CPU的支持。
线程是操作系统调度的最小单位,一个进程可以包含多个线程。线程共享进程的内存空间,因此线程间的通信比进程间的通信更加高效。进程是操作系统资源分配的最小单位,每个进程都有独立的内存空间。
线程的生命周期包括以下几个状态:
在Java中,创建线程的方式主要有两种:
Thread
类:通过继承Thread
类并重写run()
方法来创建线程。Runnable
接口:通过实现Runnable
接口并将其传递给Thread
对象来创建线程。// 方式1:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
// 方式2:实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable is running");
}
}
public class Main {
public static void main(String[] args) {
// 方式1
MyThread thread1 = new MyThread();
thread1.start();
// 方式2
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
线程的优先级决定了线程获取CPU时间片的概率。Java中线程的优先级分为1(最低)到10(最高),默认优先级为5。可以通过setPriority()
方法设置线程的优先级。
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
thread.start();
线程调度是指操作系统决定哪个线程在何时执行的过程。Java中的线程调度是抢占式的,即高优先级的线程会优先执行,但具体的调度策略取决于操作系统的实现。
线程同步是指多个线程在访问共享资源时,通过某种机制保证资源的一致性和正确性。互斥是指同一时刻只允许一个线程访问共享资源。Java中常用的同步机制包括synchronized
关键字和Lock
接口。
线程通信是指多个线程之间通过某种机制进行信息交换。Java中常用的线程通信机制包括wait()
、notify()
和notifyAll()
方法。
class SharedResource {
private boolean flag = false;
public synchronized void produce() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Produced");
flag = true;
notify();
}
public synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed");
flag = false;
notify();
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.produce();
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.consume();
}
});
producer.start();
consumer.start();
}
}
线程中的异常如果没有被捕获,会导致线程终止。可以通过UncaughtExceptionHandler
接口来捕获线程中的未捕获异常。
Thread thread = new Thread(() -> {
throw new RuntimeException("Thread exception");
});
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println("Exception in thread " + t.getName() + ": " + e.getMessage());
});
thread.start();
synchronized
关键字synchronized
关键字用于实现线程同步,可以修饰方法或代码块。修饰方法时,锁对象是当前实例;修饰静态方法时,锁对象是当前类的Class对象;修饰代码块时,锁对象是括号内的对象。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + counter.getCount());
}
}
volatile
关键字volatile
关键字用于保证变量的可见性,即一个线程对变量的修改对其他线程是可见的。volatile
还可以防止指令重排序。
class SharedResource {
private volatile boolean flag = false;
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread t1 = new Thread(() -> {
while (!resource.getFlag()) {
// 等待flag变为true
}
System.out.println("Flag is true");
});
Thread t2 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.setFlag(true);
System.out.println("Flag set to true");
});
t1.start();
t2.start();
}
}
ReentrantLock
ReentrantLock
是Lock
接口的实现类,提供了比synchronized
更灵活的锁机制。ReentrantLock
支持公平锁和非公平锁,并且可以中断等待锁的线程。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + counter.getCount());
}
}
ReadWriteLock
ReadWriteLock
接口提供了读写锁机制,允许多个读线程同时访问共享资源,但写线程独占访问。ReentrantReadWriteLock
是ReadWriteLock
的实现类。
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class SharedResource {
private int data = 0;
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void write(int data) {
lock.writeLock().lock();
try {
this.data = data;
System.out.println("Write: " + data);
} finally {
lock.writeLock().unlock();
}
}
public int read() {
lock.readLock().lock();
try {
System.out.println("Read: " + data);
return data;
} finally {
lock.readLock().unlock();
}
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread writer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.write(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread reader = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
writer.start();
reader.start();
}
}
Condition
Condition
接口提供了类似于wait()
和notify()
的线程通信机制,但更加灵活。Condition
通常与ReentrantLock
一起使用。
”`java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
class SharedResource { private boolean flag = false; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition();
public void produce() {
lock.lock();
try {
while (flag) {
condition.await();
}
System.out.println("Produced");
flag = true;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void consume() {
lock.lock();
try {
while (!flag) {
condition.await();
}
System.out.println("Consumed");
flag = false;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.produce();
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i <
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。