多种方式解答某笔试题,输入字符串“A,26,#“, 用三个线程交替打印26次Ai#, 其中i为当前打印到第几次

一、Java语言

1.使用信号量semaphore

import java.util.Scanner;
import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input=in.next();
        String[] s=input.split(",");
        int k=Integer.parseInt(s[1]);
        MyPrint myprint=new MyPrint();
        new Thread(() -> {
            try {
                myprint.printA(s[0],k);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(() -> {
            try {
                myprint.printB(k);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(() -> {
            try {
                myprint.printC(s[2],k);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
    public static class MyPrint{
        private static final Semaphore A=new Semaphore(1);
        private static final Semaphore B=new Semaphore(0);
        private static final Semaphore C=new Semaphore(0);
        public void printA(String s,int k) throws InterruptedException {
            for(int i=0;i<k;i++){
                A.acquire();
                System.out.print(s);
                try{
                    B.release();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        public void printB(int k) throws InterruptedException {
            for(int i=0;i<k;i++){
                B.acquire();
                System.out.print(i+1);
                try{
                    C.release();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        public void printC(String s,int k) throws InterruptedException {
            for(int i=0;i<k;i++){
                C.acquire();
                System.out.print(s);
                try{
                    A.release();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}

2.使用synchronized,notify()和wait()

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input=in.next();
        String[] s=input.split(",");
        int k=Integer.parseInt(s[1]);
        MyPrint myprint=new MyPrint();
        new Thread(() -> {
            myprint.printA(s[0],k);
        }).start();
        new Thread(() -> {
            myprint.printB(k);
        }).start();
        new Thread(() -> {
            myprint.printC(s[2],k);
        }).start();
    }
    public static class MyPrint{
        private static int state=1;
        private final Object lock = new Object();
        public void printA(String s,int k){
            synchronized (lock){
                for(int i=0;i<k;i++){
                    while(state!=1){
                        try{
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(s);
                    state=2;
                    lock.notifyAll();
                }
            }

        }
        public void printB(int k){
            synchronized (lock){
                for(int i=0;i<k;i++){
                    while(state!=2){
                        try{
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(i+1);
                    state=3;
                    lock.notifyAll();
                }
            }
        }
        public void printC(String s,int k){
            synchronized (lock){
                for(int i=0;i<k;i++){
                    while(state!=3){
                        try{
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(s);
                    state=1;
                    lock.notifyAll();
                }
            }
        }
    }
}

3.使用ReentrantLock和Condition

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

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input=in.next();
        String[] s=input.split(",");
        int k=Integer.parseInt(s[1]);
        MyPrint myprint=new MyPrint();
        new Thread(() -> {
            myprint.printA(s[0],k);
        }).start();
        new Thread(() -> {
            myprint.printB(k);
        }).start();
        new Thread(() -> {
            myprint.printC(s[2],k);
        }).start();
    }
    public static class MyPrint{
        private static int state=1;
        private static Lock lock=new ReentrantLock();
        private static Condition A=lock.newCondition();
        private static Condition B=lock.newCondition();
        private static Condition C=lock.newCondition();

        public void printA(String s,int k) {
            try {
                lock.lock();
                for (int i = 0; i < k; i++) {
                    while (state != 1) {
                        A.await();
                    }
                    System.out.print(s);
                    state = 2;
                    B.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        public void printB(int k){
            try {
                lock.lock();
                for (int i = 0; i < k; i++) {
                    while (state != 2) {
                        B.await();
                    }
                    System.out.print(i+1);
                    state = 3;
                    C.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        public void printC(String s,int k){
            try {
                lock.lock();
                for (int i = 0; i < k; i++) {
                    while (state != 3) {
                        C.await();
                    }
                    System.out.print(s);
                    state = 1;
                    A.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

C++语言

1.使用mutex和condition_variable

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int mod=1e9+7;
int k,state=1;//k为交替打印次数,state为当前打印线程标志
mutex my_mutex;
condition_variable cv;
vector<string> vs;//输入字符串数组

void printA(){
    unique_lock<mutex> my_guard(my_mutex);
    for(int i=0;i<k;i++){
        cv.wait(my_guard,[]()->bool {return state==1;});
        cout<<vs[0];
        state=2;
        cv.notify_all();
    }
    my_guard.unlock();
}
void printB(){
    unique_lock<mutex> my_guard(my_mutex);
    for(int i=0;i<k;i++){
        cv.wait(my_guard,[]()->bool {return state==2;});
        cout<<i+1;
        state=3;
        cv.notify_all();
    }
    my_guard.unlock();
}
void printC(){
    unique_lock<mutex> my_guard(my_mutex);
    for(int i=0;i<k;i++){
        cv.wait(my_guard,[]()->bool {return state==3;});
        cout<<vs[2];
        state=1;
        cv.notify_all();
    }
    my_guard.unlock();
}
int main() {
    string s,temp;
    cin>>s;
    stringstream st(s);
    while(getline(st,temp,',')){
        vs.push_back(temp);
    }
    k=stoi(vs[1]);
    thread threadA(printA);
    thread threadB(printB);
    thread threadC(printC);
    threadA.join();
    threadB.join();
    threadC.join();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值