Java并发知识点有哪些

发布时间:2022-03-28 16:13:49 作者:iii
来源:亿速云 阅读:158

Java并发知识点有哪些

目录

  1. 并发基础

  2. Java并发工具类

  3. Java内存模型

  4. 线程池

  5. 并发设计模式

  6. 并发编程中的常见问题

  7. 并发编程的最佳实践

  8. 并发编程的未来趋势

1. 并发基础

1.1 什么是并发

并发是指多个任务在同一时间段内交替执行,从宏观上看,这些任务似乎是同时进行的。并发编程的目的是提高程序的执行效率,充分利用多核CPU的计算能力。

1.2 并发与并行的区别

并发和并行是两个容易混淆的概念。并发是指多个任务在同一时间段内交替执行,而并行是指多个任务在同一时刻同时执行。并发可以通过时间片轮转的方式实现,而并行则需要多核CPU的支持。

1.3 线程与进程

线程是操作系统调度的最小单位,一个进程可以包含多个线程。线程共享进程的内存空间,因此线程间的通信比进程间的通信更加高效。进程是操作系统资源分配的最小单位,每个进程都有独立的内存空间。

1.4 线程的生命周期

线程的生命周期包括以下几个状态:

1.5 线程的创建方式

在Java中,创建线程的方式主要有两种:

  1. 继承Thread:通过继承Thread类并重写run()方法来创建线程。
  2. 实现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();
    }
}

1.6 线程的优先级

线程的优先级决定了线程获取CPU时间片的概率。Java中线程的优先级分为1(最低)到10(最高),默认优先级为5。可以通过setPriority()方法设置线程的优先级。

Thread thread = new Thread(() -> {
    System.out.println("Thread is running");
});
thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
thread.start();

1.7 线程的调度

线程调度是指操作系统决定哪个线程在何时执行的过程。Java中的线程调度是抢占式的,即高优先级的线程会优先执行,但具体的调度策略取决于操作系统的实现。

1.8 线程的同步与互斥

线程同步是指多个线程在访问共享资源时,通过某种机制保证资源的一致性和正确性。互斥是指同一时刻只允许一个线程访问共享资源。Java中常用的同步机制包括synchronized关键字和Lock接口。

1.9 线程的通信

线程通信是指多个线程之间通过某种机制进行信息交换。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();
    }
}

1.10 线程的异常处理

线程中的异常如果没有被捕获,会导致线程终止。可以通过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();

2. Java并发工具类

2.1 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());
    }
}

2.2 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();
    }
}

2.3 ReentrantLock

ReentrantLockLock接口的实现类,提供了比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());
    }
}

2.4 ReadWriteLock

ReadWriteLock接口提供了读写锁机制,允许多个读线程同时访问共享资源,但写线程独占访问。ReentrantReadWriteLockReadWriteLock的实现类。

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();
    }
}

2.5 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 < 
推荐阅读:
  1. javaSE知识点有哪些
  2. mysql知识点有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:PHP格式字串可以识别哪些format参数

下一篇:PHP的include和require语句有什么作用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》