Java

java多线程同步怎么实现

小樊
83
2024-09-02 05:15:31
栏目: 编程语言

在Java中,可以通过以下几种方式实现多线程同步:

  1. 使用synchronized关键字:

synchronized关键字可以用于修饰方法或者代码块,当一个线程访问被synchronized修饰的方法或代码块时,其他线程将无法访问该方法或代码块。这样可以确保同一时间只有一个线程能够访问共享资源。

示例:

public class SynchronizedExample {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Counter: " + counter.getCount());
    }
}

class Counter {
    private int count;

    public synchronized void increase() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}
  1. 使用Lock接口和ReentrantLock类:

Java提供了Lock接口和ReentrantLock类来实现更灵活的线程同步。与synchronized相比,Lock提供了更高的灵活性,例如可以尝试获取锁、定时获取锁和可中断获取锁等操作。

示例:

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

public class LockExample {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Counter: " + counter.getCount());
    }
}

class Counter {
    private int count;
    private Lock lock = new ReentrantLock();

    public void increase() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
}
  1. 使用java.util.concurrent包中的高级同步工具:

Java提供了许多高级的同步工具,如Semaphore、CountDownLatch、CyclicBarrier等。这些工具可以帮助您更容易地实现复杂的多线程同步需求。

示例(使用CountDownLatch):

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) {
        Counter counter = new Counter();
        CountDownLatch latch = new CountDownLatch(2);

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
                latch.countDown();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counter.increase();
                }
                latch.countDown();
            }
        });

        t1.start();
        t2.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Counter: " + counter.getCount());
    }
}

class Counter {
    private int count;

    public synchronized void increase() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

以上就是Java中实现多线程同步的几种方法。在实际应用中,可以根据具体需求选择合适的同步方式。

0
看了该问题的人还看了