对于多线程编程,你理解Java中的synchronized关键字吗?请举例说明。

原创 朴灿烈づ我的快乐病毒、 2025-03-23 04:36 52阅读 0赞

synchronized关键字是Java中用于实现线程同步的关键字。它主要用于修饰方法或者代码块,以确保在同一时间只有一个线程能够访问被synchronized修饰的代码。

以下是一些例子:

  1. 修饰方法:

    1. public class Counter {
    2. private int count = 0;
    3. // synchronized method to increment count
    4. public synchronized void increment() {
    5. count++;
    6. }
    7. // example usage: multiple threads can call increment(), but only one thread at a time
    8. public static void main(String[] args) {
    9. Counter counter = new Counter();
    10. Thread thread1 = new Thread(() -> {
    11. for (int i = 0; i < 10; i++) {
    12. counter.increment();
    13. }
    14. }));
    15. Thread thread2 = new Thread(() -> {
    16. for (int i = 0; i < 5; i++) {
    17. counter.increment();
    18. }
    19. }));
    20. thread1.start();
    21. thread2.start();
    22. // wait until both threads finish
    23. try {
    24. thread1.join();
    25. thread2.join();
    26. } catch (InterruptedException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }
  2. 修饰代码块:

    1. public class PrintCounter {
    2. private int count = 0;
    3. // synchronized code block to print count
    4. public synchronized void printCount() {
    5. System.out.println("Count: " + count);
    6. }
    7. // example usage: multiple threads can call printCount(), but only one thread at a time
    8. public static void main(String[] args) {
    9. PrintCounter counter = new PrintCounter();
    10. Thread thread1 = new Thread(() -> {
    11. for (int i = 0; i < 5; i++) {
    12. counter.printCount();
    13. }
    14. }));
    15. Thread thread2 = new Thread(() -> {
    16. for (int i = 0; i < 10; i++) {
    17. counter.printCount();
    18. }
    19. }));
    20. thread1.start();
    21. thread2.start();
    22. // wait until both threads finish
    23. try {
    24. thread1.join();
    25. thread2.join();
    26. } catch (InterruptedException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }

    以上例子展示了如何使用synchronized关键字来实现线程同步,确保同一时间只有一个线程可以访问共享资源。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,52人围观)

还没有评论,来说两句吧...

相关阅读