Welcome to

Vcode

首页 / Java / 闲来无事系列-多线程交替打印奇偶数

闲来无事系列-多线程交替打印奇偶数

不多说 直接上代码 ,简单粗暴:

package com.plzero.pack1;

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

public class ThreadDemo {
    public static void main(String[] args) {
        Nums num = new Nums();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    num.printSingle(i);
                }
            }
        }).start();//打印奇数

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    num.printNosinale(i);
                }

            }
        }).start();//打印偶数
    }

    static class Nums {

        int A = 0;
        int B = 0;
        boolean flag = false;//等待标志
        Lock lock = new ReentrantLock();
        Condition single = lock.newCondition();
        Condition nosingle = lock.newCondition();

        void printSingle(int i) {
            lock.lock();
            try {
                if (flag) {
                    single.await();
                }
                A = 2 * i + 1;
                System.out.println("奇数: " + A);
                Thread.sleep(200);
                flag = true;
                nosingle.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }


        void printNosinale(int i) {
            lock.lock();
            try {
                if (!flag) {
                    nosingle.await();
                }
                B = 2 * i + 2;
                System.out.println("偶数: " + B);
                Thread.sleep(200);
                single.signal();
                flag = false;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }
}


image.png

本文暂无评论

发表评论

您的电子邮件地址不会被发布。

>> <<