Java多线程同步问题:竞态条件示例

原创 妖狐艹你老母 2024-09-27 10:45 207阅读 0赞

在Java多线程编程中,竞态条件是指两个或更多的线程对同一资源进行操作,由于它们的执行顺序不确定,从而导致结果不一致的问题。

下面是一个简单的竞态条件示例:

  1. class Counter {
  2. int count = 0;
  3. synchronized void increment() {
  4. count++;
  5. notifyAll(); // 通知所有等待的线程
  6. }
  7. synchronized void decrement() {
  8. count--;
  9. if (count == 0) { // 如果计数为0,说明资源可用
  10. notifyAll();
  11. }
  12. }
  13. }
  14. public class Main {
  15. public static void main(String[] args) {
  16. Counter counter = new Counter();
  17. Thread thread1 = new Thread(() -> {
  18. for (int i = 0; i < 5; i++) {
  19. counter.increment(); // 执行增操作
  20. try {
  21. // 线程休眠一段时间,模拟资源的可用性
  22. Thread.sleep(200);
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }));
  28. Thread thread2 = new Thread(() -> {
  29. for (int i = 0; i < 5; i++) {
  30. counter.decrement(); // 执行减操作
  31. try {
  32. // 线程休眠一段时间,模拟资源的不可用性
  33. Thread.sleep(200);
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }));
  39. thread1.start();
  40. thread2.start();
  41. try {
  42. // 主线程等待两个子线程执行完毕
  43. thread1.join();
  44. thread2.join();
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. System.out.println("Final count: " + counter.count);
  49. }
  50. }

在这个示例中,Counter类的两个方法increment()decrement()分别模拟了资源的增操作和减操作。由于线程的执行顺序不确定,可能会出现先执行减操作导致结果不正确的问题。

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

发表评论

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

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

相关阅读