多线程实现奇偶数的交替打印

  1. 创建打印0~50之间的奇数线程
/**
 * 奇数线程类
 */
public class OddThread extends Thread {
    @Override
    public void run() {
        /*for (int i = 1; i < 50; i++) {
            if (i % 2 != 0) {
                System.out.println(" 奇数线程中i = " + i);
            }
        }*/
        for (int i = 1; i < 50; i += 2) {
            System.out.println(" 奇数线程中i = " + i);
        }
    }
}
  1. 创建打印0~50之间的偶数线程
/**
 * 偶数线程类
 */
public class EvenThread extends Thread {
    @Override
    public void run() {
        /*for (int i = 2; i < 50; i++) {
            if (i % 2 == 0) {
                System.out.println(" -----偶数线程中i = " + i);
            }
            // System.out.println(" -----偶数线程中i = " + i);
        }*/
        for (int i = 2; i < 50; i += 2) {
            System.out.println(" -----偶数线程中i = " + i);
        }
    }
}
  1. 测试类
public class OddEvenThreadTest {

    public static void main(String[] args) {
        EvenThread et = new EvenThread();
        OddThread ot = new OddThread();

        // 启动两个线程
        et.start();
        ot.start();

        System.out.println(" 主线程开始等待 ");
        try {
            // 调用join方法保证两个线程顺序执行,交替打印奇偶数
            et.join();
            ot.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" 主线程等待结束 ");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,这是一个经典的多线程问题,可以使用线程同步的方式解决。具体实现如下: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int count = 1; void *print_odd(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); if (count % 2 != 0) { printf("Thread 1: %d\n", count++); pthread_cond_signal(&cond); } else { pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex); } return NULL; } void *print_even(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); if (count % 2 == 0) { printf("Thread 2: %d\n", count++); pthread_cond_signal(&cond); } else { pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t tid1, tid2; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&tid1, NULL, print_odd, NULL); pthread_create(&tid2, NULL, print_even, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } ``` 这段代码中,我们使用了一个互斥锁和条件变量,其中互斥锁用于保护共享变量 count 的访问,条件变量用于线程之间的通信。两个线程分别打印和偶,通过对 count 取模的方式来确定哪个线程应该打印值。如果当前不是该线程打印值,就等待条件变量的信号,否则就打印值并发送信号给另一个线程。注意,线程之间的通信必须在互斥锁的保护下进行,以避免竞争条件的发生。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个射手座的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值