多线程循环打印ABC

多线程循环打印ABC

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

public class ABC_Lock {
    private static Lock lock = new ReentrantLock();// 通过JDK5中的Lock锁来保证线程的访问的互斥
    private static int state = 0;//通过state的值来确定是否打印

    static class ThreadA extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 0) {// 多线程并发,不能用if,必须用循环测试等待条件,避免虚假唤醒
                        System.out.print("A");
                        state++;
                        i++;
                    }
                } finally {
                    lock.unlock();// unlock()操作必须放在finally块中
                }
            }
        }
    }

    static class ThreadB extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 1) {// 多线程并发,不能用if,必须用循环测试等待条件,避免虚假唤醒
                        System.out.print("B");
                        state++;
                        i++;
                    }
                } finally {
                    lock.unlock();// unlock()操作必须放在finally块中
                }
            }
        }
    }

    static class ThreadC extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 2) {// 多线程并发,不能用if,必须用循环测试等待条件,避免虚假唤醒
                        System.out.print("C");
                        state++;
                        i++;
                    }
                } finally {
                    lock.unlock();// unlock()操作必须放在finally块中
                }
            }
        }
    }

    public static void main(String[] args) {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }
}
在 C 语言中实现三个线程循环顺序打印 ABC 的需求,可以通过多种同步机制来实现。由于线程调度的不确定性,必须引入同步机制来控制线程的执行顺序,确保打印按照 ABCABCABC 的顺序进行。常见的实现方式包括使用互斥锁(mutex)和条件变量(condition variable)[^1]。 以下是一个使用互斥锁和条件变量实现的示例代码: ```c #include <stdio.h> #include <pthread.h> #define TOTAL_LOOPS 10 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_a = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_b = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_c = PTHREAD_COND_INITIALIZER; int state = 0; // 0 for A, 1 for B, 2 for C void* print_a(void* arg) { for (int i = 0; i < TOTAL_LOOPS; ++i) { pthread_mutex_lock(&mutex); while (state != 0) { pthread_cond_wait(&cond_a, &mutex); } printf("A"); state = 1; pthread_cond_signal(&cond_b); pthread_mutex_unlock(&mutex); } return NULL; } void* print_b(void* arg) { for (int i = 0; i < TOTAL_LOOPS; ++i) { pthread_mutex_lock(&mutex); while (state != 1) { pthread_cond_wait(&cond_b, &mutex); } printf("B"); state = 2; pthread_cond_signal(&cond_c); pthread_mutex_unlock(&mutex); } return NULL; } void* print_c(void* arg) { for (int i = 0; i < TOTAL_LOOPS; ++i) { pthread_mutex_lock(&mutex); while (state != 2) { pthread_cond_wait(&cond_c, &mutex); } printf("C"); state = 0; pthread_cond_signal(&cond_a); pthread_mutex_unlock(&mutex); } printf("\n打印完毕\n"); return NULL; } int main() { pthread_t thread_a, thread_b, thread_c; pthread_create(&thread_a, NULL, print_a, NULL); pthread_create(&thread_b, NULL, print_b, NULL); pthread_create(&thread_c, NULL, print_c, NULL); pthread_join(thread_a, NULL); pthread_join(thread_b, NULL); pthread_join(thread_c, NULL); return 0; } ``` 上述代码中,通过 `pthread_mutex_lock` 和 `pthread_cond_wait` 实现了线程的等待与唤醒机制。每个线程在进入临界区之前会检查 `state` 的值,只有当 `state` 的值匹配时才会执行打印操作,并通过 `pthread_cond_signal` 唤醒下一个线程继续执行。这种机制确保了线程的执行顺序为 ABCABCABC,直到完成 10 轮打印后输出“打印完毕”[^2]。 另一种实现方式是使用信号量(semaphore),通过控制信号量的值来协调线程的执行顺序。然而,在 C 语言中使用信号量通常需要引入额外的头文件(如 `<semaphore.h>`),并且在某些系统上可能不完全支持[^2]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值