两个线程交替打印奇偶数

在做这个代码之前,其实碰到了一些问题,不过说到底还是基础不行,总结出来就是 切不要以Integer等作为锁的对象,也就是
被锁住的引用 所指向的对象一定不能变,用integer极其容易引起所指向对象的改变 如 i = i+1;等等 切记 切记 。否则会报错哦,(非法对象监视器异常)

例如 : 有个Integer i对象
 synchronized (i) {
  i =i+1;
 i.wait(); //注意这里 i所指向的对象改变, 线程并没有获取到 i重新指 向对象的锁,故会报错 )
}



wait(),notity(),notityAll()的具体使用方法 参考本篇文章  https://yq.aliyun.com/articles/1419 

package com.test;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTest {
    public volatile static boolean flag1 = true;
    public volatile static AtomicInteger i = new AtomicInteger(0); //这里为了方便直接使用原子类,
                                                                    //其实可以创建一个对象
                                                                   //该对象有一个int属性即可 ;
    public static void main(String[] args) {
        Thread thread1 = new Thread1();
            Thread thread2 = new Thread2();
        thread1.start();
            thread2.start();
           

    }

    static class Thread1 extends Thread {

        @Override
        public void run() {
            while (i.get() < 10) {
                synchronized (i) {
                    try {
                        while (i.get()
                                % 2 == 0) {
                            System.out.println(Thread.currentThread() + ":" + i);
                            i.incrementAndGet();
                         //   System.out.println("2222");

                            i.notify();  //唤醒对象等待队列中的一个等待的线程


                        }
                        while (i.get() % 2 != 0) {
                            i.wait();  //奇数 , wait暂时释放锁 ,成为阻塞状态
                        }



                    } catch (InterruptedException e) { //这里抓捕异常 一般不会进入这里
                        
                        e.printStackTrace();
                    }
                }
            }
            flag1 = false;

        }

        @Override
        public String toString() {
            return "Thread-1";
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            while (i.get() < 10){
                synchronized (i) {
                    try {
                        while (i.get() % 2 != 0) {
                           // System.out.println("第二个");
                            System.out.println(Thread.currentThread() + ":" + i);
                            i.incrementAndGet();
                            i.notify(); //唤醒对象等待队列中的一个等待的线程


                        }

                        if(i.get()%2==0){
                            i.wait(); //偶数 , wait暂时释放锁 ,成为阻塞状态
                        }

                    } catch (InterruptedException e1) {
                       // System.out.println("第二个线程堵死");
                        e1.printStackTrace();
                    }


                }

        }
    }

    @Override
    public String toString() {
        return "Thread-2";
    }
}


}

最后还有一点值得注意的是这里会造成一个线程一直处于阻塞状态,造成原因是,当一个线程满足条件后退出,造成阻塞的线程会一直没有人唤醒。 
以下是使用 POSIX 线程库实现的 Linux 双线程交替打印奇偶的示例代码: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 初始化条件变量 int count = 0; // 打印器 void *print_even(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); // 加锁 if (count % 2 == 0) { // 判断是否为偶 printf("even thread: %d\n", count); count++; pthread_cond_signal(&cond); // 发送信号 } else { pthread_cond_wait(&cond, &mutex); // 等待信号 } pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } void *print_odd(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); // 加锁 if (count % 2 == 1) { // 判断是否为奇 printf("odd thread: %d\n", count); count++; pthread_cond_signal(&cond); // 发送信号 } else { pthread_cond_wait(&cond, &mutex); // 等待信号 } pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, print_even, NULL); // 创建偶线程 pthread_create(&tid2, NULL, print_odd, NULL); // 创建奇线程 pthread_join(tid1, NULL); // 等待线程结束 pthread_join(tid2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥锁 pthread_cond_destroy(&cond); // 销毁条件变量 return 0; } ``` 上述代码中,我们使用了互斥锁和条件变量来实现线程间的同步和通信。其中,互斥锁用来保护打印器 `count` 的访问,条件变量用来等待和发送信号。在偶线程中,如果当前的 `count` 为偶,则打印并将 `count` 加 1,并发送信号通知奇线程;否则等待奇线程发送信号。在奇线程中,如果当前的 `count` 为奇,则打印并将 `count` 加 1,并发送信号通知偶线程;否则等待偶线程发送信号。最后,我们使用 `pthread_join` 函等待两个线程结束,并销毁互斥锁和条件变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值