实现多线程对同一个变量线程共享

在Java中,可以使用synchronized关键字或ReentrantLock类来解决多线程访问同一个变量时可能出现的数据不一致问题。以下是使用synchronized关键字的示例代码:

public class ThreadExample {
    private static int count = 0;
    
    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 0; i < 10000; i++) {
                incrementCount();
            }
        };
        
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        
        thread1.start();
        thread2.start();
        
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Final count: " + count);
    }
    
    private synchronized static void incrementCount() {
        count++;
    }
}

在上面的示例中,我们使用synchronized关键字修饰incrementCount()方法,确保同时只有一个线程可以访问该方法,从而避免线程共享带来的数据不一致问题。

另外,还可以使用ReentrantLock类来实现线程同步,以下是使用ReentrantLock的示例代码:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadExample {
    private static int count = 0;
    private static Lock lock = new ReentrantLock();
    
    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 0; i < 10000; i++) {
                incrementCount();
            }
        };
        
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        
        thread1.start();
        thread2.start();
        
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Final count: " + count);
    }
    
    private static void incrementCount() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

在上面的示例中,我们创建了一个ReentrantLock对象lock,然后在incrementCount()方法中使用lock()unlock()方法来确保线程安全。

你可能感兴趣的:(JavaWeb,java,开发语言)