首页 > 试题广场 >

多线程

[编程题]多线程
  • 热度指数:45263 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。[注:C语言选手可使用WINDOWS SDK库函数]
接口说明:
void init();  //初始化函数
void Release(); //资源释放函数
unsignedint__stdcall ThreadFun1(PVOID pM)  ; //线程函数1,传入一个int类型的指针[取值范围:1 – 250,测试用例保证],用于初始化输出A次数,资源需要线程释放
unsignedint__stdcall ThreadFun2(PVOID pM)  ;//线程函数2,无参数传入
unsignedint__stdcall ThreadFun3(PVOID pM)  ;//线程函数3,无参数传入
Unsigned int __stdcall ThreadFunc4(PVOID pM);//线程函数4,无参数传入
char  g_write[1032]; //线程1,2,3,4按顺序向该数组赋值。不用考虑数组是否越界,测试用例保证


输入描述:

本题含有多个样例输入。
输入一个int整数



输出描述:

对于每组样例,输出多个ABCD

示例1

输入

10

输出

ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
各位大神看看,为什么时间复杂度太高,一直错误???
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main extends Thread {
	
	
	private String name;
	private Object pre;
	private Object self;
	private int count;
	
	Main(String name, Object pre, Object self, int count) {
		this.name = name;
		this.pre = pre;
		this.self = self;
		this.count = count;
	}
	
	public void run(){
		while(count>0){
			synchronized(pre){
				synchronized(self){
					System.out.print(name);
					count--;
					self.notifyAll();
				}
				try {
					pre.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException,IOException {
		

		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		int count = Integer.valueOf(br.readLine());
		
		Object a = new Object();
		Object b = new Object();
		Object c = new Object();
		Object d = new Object();
		
		Thread pa = new Main("A",d,a,count);
		Thread pb = new Main("B",a,b,count); Thread pc = new Main("C",b,c,count); Thread pd = new Main("D",c,d,count);
		
		pa.start();
		pa.sleep(10);
		
		pb.start();
		pb.sleep(10);
		
		pc.start();
		pc.sleep(10);
		
		pd.start();
		pd.sleep(10);
		
	}
		
}

发表于 2017-08-18 16:53:22 回复(0)
更多回答
#include<iostream>
#include<mutex>
#include<condition_variable>
#include<string>
#include<thread>
using namespace std;
string res("");
mutex mtx;
bool done = false;
condition_variable A, B, C, D;
void fun_A(int times) {
	while (times--) {
		unique_lock<mutex> locker(mtx);
		A.wait(locker);
		res += 'A';
		B.notify_one();
	}
	done = true;
}
void fun_B() {
	while (!done) {
		unique_lock<mutex> locker(mtx);
		B.wait(locker);
		res += 'B';
		C.notify_one();
	}
}
void fun_C() {
	while (!done) {
		unique_lock<mutex> locker(mtx);
		C.wait(locker);
		res += 'C';
		D.notify_one();
	}
}
void fun_D() {
	while (!done) {
		unique_lock<mutex> locker(mtx);
		D.wait(locker);
		res += 'D';
		A.notify_one();
	}
}
int main() {
	int num;
	while (cin >> num) {
		res = "";
		thread t1(fun_A, num);
		thread t2(fun_B);
		thread t3(fun_C);
		thread t4(fun_D);
		A.notify_one();
		t1.join();
		t2.join();
		t3.join();
		t4.join();
		cout << res << endl;
		done = false;
	}
	return 0;
}

发表于 2017-03-17 14:13:43 回复(19)
python3怎么处理多线程问题啊? 有懂的帮忙回答一下啊
发表于 2021-07-13 23:28:41 回复(1)
package com.thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MyThreadPrinter2 implements Runnable {

	private String name;
	private Object prev;
	private Object self;
	private int count;
	private MyThreadPrinter2(String name, Object prev, Object self, int count) {
		this.name = name;
		this.prev = prev;
		this.self = self;
		this.count = count;
	}
	@Override
	public void run() {
		// int count = 10;
		while (count > 0) {
			synchronized (prev) {
				synchronized (self) {
					System.out.print(name);
					count--;
					self.notify();
				}
				try {
					prev.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) throws Exception {
		Object a = new Object();
		Object b = new Object();
		Object c = new Object();
		Object d = new Object();
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		int count = Integer.valueOf(br.readLine());
		MyThreadPrinter2 pa = new MyThreadPrinter2("A", d, a, count);
		MyThreadPrinter2 pb = new MyThreadPrinter2("B", a, b, count);
		MyThreadPrinter2 pc = new MyThreadPrinter2("C", b, c, count);
		MyThreadPrinter2 pd = new MyThreadPrinter2("D", c, d, count);
		
		new Thread(pa).start();
		Thread.sleep(100); // 确保按顺序A、B、C执行
		new Thread(pb).start();
		Thread.sleep(100);
		new Thread(pc).start();
		Thread.sleep(100);
		new Thread(pd).start();
	}
}
发表于 2016-08-02 17:43:59 回复(10)
# python 版本的多线程实现。虽然可以直接输出,但是就没有达到考察的效果了。
import threading
#import time

class MyThread1(threading.Thread):
    def run(self):
        global g_write, mutex, ins
        #time.sleep(1)
        while ins>0:
            if mutex.acquire(1):
                if g_write[-1] == "D":
                    g_write.append("A")                    
                mutex.release()
        
class MyThread2(threading.Thread):
    def run(self):
        global g_write, mutex, ins
        #time.sleep(1)
        while ins>0:
            if mutex.acquire(1):
                if g_write[-1] == "A":
                    g_write.append("B")
                mutex.release()
        

class MyThread3(threading.Thread):
    def run(self):
        global g_write, mutex, ins
        while ins>0:
            if mutex.acquire(1):
                if g_write[-1] == "B":
                    g_write.append("C")
                mutex.release()
        
class MyThread4(threading.Thread):
    def run(self):
        global g_write, mutex, ins
        while ins>0:
            if mutex.acquire(1):
                if g_write[-1] == "C":
                    g_write.append("D")
                    ins -= 1
                    if ins <= 0:
                        print ''.join(g_write)
                        mutex.release()
                        break;
                mutex.release()
        
        
        
        
while True:
    try:
        ins = input()
    except:
        break;
    g_write = ["A"]

    mutex = threading.Lock()
    tsk = []
    tsk.append(MyThread1()) 
    tsk.append(MyThread2())
    tsk.append(MyThread3())
    tsk.append(MyThread4())

    for each in tsk:
        each.start()
    for each in tsk:
        each.join()


    
    
    

发表于 2019-06-10 16:52:30 回复(2)
import java.util.Scanner;

public class Code035 {
    private final static int THREAD_NUM = 4;
    private static char[] chs = new char[1032*THREAD_NUM];
    public static void main(String[] args) {
        createThreads();
        Scanner sc  = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            System.out.println(new String(chs).substring(0, n*THREAD_NUM));
        }
        sc.close();
    }
    
    //创建线程并进行调用
    private static void createThreads(){
        char ch = 'A';
        for(int i = 0; i < THREAD_NUM; i++){
            new Thread(new InnerThread(ch++, i)).start();
        }
    }
    
    //内部线程类
    private static class InnerThread implements Runnable{
        private char ch;
        private int index;
        public InnerThread(char ch, int index){
            this.ch = ch;
            this.index = index;
        }
        
        public void run() {
            while(this.index < chs.length){
                chs[this.index] = this.ch;
                this.index += THREAD_NUM;
            }
        }
    }

}

编辑于 2018-02-23 12:05:33 回复(0)
import java.util.*;
//临界资源
class CharBuffer{
    private StringBuffer value = new StringBuffer();//共享变量
    private int num = 0;                            //添加次数
    private int order = 0;                             //信号量,约定发送线程的次序

    public String getVal(){
        return value.toString();
    }
    public CharBuffer(int num){
        this.num = num;
    }
    //临界区
    public synchronized void put(char c,int order){
        if(this.order != order){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return;
        }
        value.append(c);                  //将字母添加到共享资源
        this.order = (this.order + 1) % 4;
        if(this.order == 0)
            num --;
        this.notifyAll();
    }

    public int getNum(){
        return num;
    }

}
//发送线程
class SendThread extends Thread{
    private CharBuffer cb;
    private int order = 0;         //信号量,约定发送线程次序
    private char c;
    public SendThread(char c,int order,CharBuffer cb){
        this.c = c;
        this.order = order;
        this.cb = cb;
    }

    public void run(){
        while(cb.getNum() != 0){
            cb.put(c,order);
        }
    }
}
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            CharBuffer cb = new CharBuffer(n);
            //创建线程
            SendThread st1 = new SendThread('A',0,cb);
            st1.start();
            SendThread st2 = new SendThread('B',1,cb);
            st2.start();
            SendThread st3 = new SendThread('C',2,cb);
            st3.start();
            SendThread st4 = new SendThread('D',3,cb);
            st4.start();
            try {
                //等待4个线程运行结束
                st1.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(cb.getVal());
        }
    }
}
编辑于 2017-09-19 21:39:37 回复(2)
两种方法,第一种是2次synchronize+wait+notify 实现,这种超时了,其实感觉没问题的。idea上过了。也判断了最后一次。第二种看到别人写的用线程池,还行。
/*两个锁时间复杂度太高
import java.util.*;
public class Main {
    public static class MyThread extends Thread{
        private String name;
        private Object prev;
        private Object self;
        private int count;

        public MyThread(String name, Object prev, Object self, int count) {
            this.name = name;
            this.prev = prev;
            this.self = self;
            this.count = count;
        }

        @Override
        public void run(){
            while(count>0){
                synchronized (prev){
                    synchronized (self){
                        count--;
                        System.out.print(name);
                        self.notify();
                    }
                    if(count>0){
                        try{
                            prev.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Object a=new Object();
        Object b=new Object();
        Object c=new Object();
        Object d=new Object();
        while (sc.hasNext()) {
            int n = sc.nextInt();
            new MyThread("A",d,a,n).start();
            try {
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            new MyThread("B",a,b,n).start();
            try {
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            new MyThread("C",b,c,n).start();
            try {
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            new MyThread("D",c,d,n).start();
        }
    }
}*/
//线程池
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Myrunnable implements Runnable{
    public String output;
    public Myrunnable(String output){
        this.output = output;
    } 
    public void run(){
        System.out.print(output);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        while(in.hasNextInt()) {
            int n=in.nextInt();
            for (int i = 0; i < n; i++) {
                threadPool.execute(new Myrunnable("A"));
                threadPool.execute(new Myrunnable("B"));
                threadPool.execute(new Myrunnable("C"));
                threadPool.execute(new Myrunnable("D"));
            }
            try{
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println();
        }
        threadPool.shutdown();
    }
}

 
发表于 2020-02-18 23:27:45 回复(0)
以前面试遇到的问题,在这儿虽然无法通过测试,但本地运行是完全正确的,而且只使用了一个锁。对大家肯定是有参考意义的!
import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main{
    
    public static void main(String []args) throws InterruptedException{  Scanner scanner=new Scanner(System.in);
        int printCount=scanner.nextInt();
        ThreadGroup group = new ThreadGroup("xx");
        // 写锁
        ReentrantLock lock = new ReentrantLock();
        // 打印a线程的condition
        Condition conditionA = lock.newCondition();
        // 打印b线程的condition
        Condition conditionB = lock.newCondition();
        // 打印c线程的condition
        Condition conditionC = lock.newCondition();
        // 打印d线程的condition
        Condition conditionD = lock.newCondition();
        // 实例化A线程
        Thread printerA = new Thread(group, new Printer(printCount,lock, conditionA, conditionB, 'A'));
        // 实例化B线程
        Thread printerB = new Thread(group, new Printer(printCount,lock, conditionB, conditionC, 'B'));
        // 实例化C线程
        Thread printerC = new Thread(group, new Printer(printCount,lock, conditionC, conditionD, 'C'));
        // 实例化D线程
        Thread printerD = new Thread(group, new Printer(printCount,lock, conditionD, conditionA, 'D'));
        // 依次开始A B C线程
        printerA.start();
        Thread.sleep(100);
        printerB.start();
        Thread.sleep(100);
        printerC.start();
        Thread.sleep(100);
        printerD.start();
        // 主线程循环让出CPU使用权
        while (group.activeCount() > 0) {
            Thread.yield();
        }
    }
    
    private static class Printer implements Runnable {
        // 打印次数
        private final int printCount;
        // 打印锁
        private final ReentrantLock reentrantLock;
        // 本线程打印所需的condition
        private final Condition thisCondtion;
        // 下一个线程打印所需要的condition
        private final Condition nextCondtion;
        // 打印字符
        private final char printChar;

        public Printer(int printCount,ReentrantLock reentrantLock, Condition thisCondtion, Condition nextCondition, char printChar) {
            this.printCount=printCount;
            this.reentrantLock = reentrantLock;
            this.nextCondtion = nextCondition;
            this.thisCondtion = thisCondtion;
            this.printChar = printChar;
        } @Override public void run() {
            // 获取打印锁 进入临界区
            reentrantLock.lock();
            try {
                // 连续打印PRINT_COUNT次
                for (int i = 0; i < printCount; i++) {
                    System.out.print(printChar);
                    // 使用nextCondition唤醒下一个线程
                    // 因为只有一个线程在等待,所以signal或者signalAll都可以
                    nextCondtion.signal();
                    // 不是最后一次则通过thisCondtion等待被唤醒
                    // 必须要加判断,不然能够打印完后就会直接死锁
                    if (i < printCount - 1) {
                        try {
                            // 本线程让出锁并等待唤醒
                            thisCondtion.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            } finally {
                // 释放打印锁
                reentrantLock.unlock();
            }
        }
    }
    
}
编辑于 2017-12-20 16:40:41 回复(2)
package Thread;

import java.util.*;

class Msg{//编写一个包含共享数据的类,各个线程操作其中的数据
    public char[] strbf;//写入这个字符数组
    public int index=1;//控制由哪个线程进行操控该数据类对象
    public int num;//用户输入的组数
    public int count=0;//数组下标计数

    public Msg(int num){//初始化
        this.num = num;
        this.index = 1;
        this.count = 0;
        this.strbf = new char[4*num];
    }
    
    public  synchronized void appendA(){//当某个对象的一个方法被同步后,该对象的其他方法不能被别的线程访问
        while(this.count<this.num*4) {//一定是当前计数还没计满时操作
            while(this.index!=1){//非对应线程等待,一定要用while,防止线程A再次获得对象锁
                if(this.count==this.num*4) { //加条件退出,让线程满足条件时跳出销毁   
                    break;
                }
                try{
                   this.wait(); //释放对象锁
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(this.count==this.num*4) {   //加条件退出,让线程满足条件时跳出销毁   
                System.out.println("A"+this.count);//在线编程说有数组越界问题,我表示抗议,这里的输出结果说明没有数组越界问题
                break;
            }
            this.strbf[count] = 'A';//对应线程进行操作
            this.count++;//计数加一
            this.index = 2;//指定下一个线程的标记
            this.notifyAll();//唤醒别的线程,不立即释放对象锁
        }
        System.out.println(this.strbf);
    }
    public  synchronized void appendB(){
        while(this.count<this.num*4) {
            while(this.index!=2){
                if(this.count==this.num*4) {    
                    break;
                }
                try{
                   this.wait(); 
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(this.count==this.num*4) {   
                System.out.println("B"+this.count);
                break;
            }
            this.strbf[count] = 'B';
            this.count++;
            this.index = 3;
            this.notifyAll();
        }
    }
    public synchronized  void appendC(){
        while(this.count<this.num*4) {
            while(this.index!=3){
                if(this.count==this.num*4) {    
                    break;
                }
                try{
                   this.wait(); 
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(this.count==this.num*4) {   
                System.out.println("C"+this.count);
                break;
            }
            this.strbf[count] = 'C';
            this.count++;
            this.index = 4;
            this.notifyAll();
        }
    }
    public  synchronized void appendD(){
        while(this.count<this.num*4) {
            while(this.index!=4){
                if(this.count==this.num*4) {    
                    break;
                }
                try{
                   this.wait(); 
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(this.count==this.num*4) {   
                System.out.println("D"+this.count);
                break;
            }
            this.strbf[count] = 'D';
            this.count++;
            this.index = 1;
            this.notifyAll();
        }
    }
}

class trdA implements Runnable{
    private Msg msg = null;
    public trdA(Msg msg){
        this.msg = msg;
    }
    public void run(){
        this.msg.appendA();
    }
}

class trdB implements Runnable{
    private Msg msg = null;
    public trdB(Msg msg){
        this.msg = msg;
    }
    public void run(){
        this.msg.appendB();
    }
}

class trdC implements Runnable{
    private Msg msg = null;
    public trdC(Msg msg){
        this.msg = msg;
    }
    public void run(){
        this.msg.appendC();
    }
}

class trdD implements Runnable{
    private Msg msg = null;
    public trdD(Msg msg){
        this.msg = msg;
    }
    public void run(){
        this.msg.appendD();
    }
}

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);//第一步,获取输入的参数
        Msg msg = null;
        while(sc.hasNext()){
            int num = sc.nextInt();
            msg = new Msg(num);
            Thread t1 = new Thread(new trdA(msg));
            t1.start();
            Thread t2 = new Thread(new trdB(msg));
            t2.start();
            Thread t3 = new Thread(new trdC(msg));
            t3.start();
            Thread t4 = new Thread(new trdD(msg));
            t4.start();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("t1:"+t1.isAlive());
            System.out.println("t2:"+t2.isAlive());
            System.out.println("t3:"+t3.isAlive());
            System.out.println("t4:"+t4.isAlive());
            System.out.println(Thread.currentThread().getName());
            
        }
    }
}

编辑于 2016-09-04 20:32:36 回复(2)
#include<iostream>

int main()
{
    int n;
    while(std::cin>>n)
    {
        for(int i =1;i<=n;++i)
            std::cout<<"ABCD";
        std::cout<<std::endl;
    }
    return 0;
}

发表于 2016-07-07 13:58:55 回复(18)
while True:
    try:
        import threading
        arr = []
        def add_char(char):
            global arr
            arr.append(char)
        for _ in range(int(input().strip())):
            for i in ['A', 'B', 'C', 'D']:
                t = threading.Thread(target=add_char, args=(i, ))
                t.start()
                t.join()
        print(''.join(arr))
    except:
        break
设置一个全局变量,存放array。随后创建线程,调用add_char函数,将线程通过join来按顺序执行。
发表于 2019-11-17 12:26:23 回复(8)

这是真线程,不取巧

import threading
import sys

def out_A(num):
    for i in range(num):
        lock1.acquire()
        print('A', end='')
        lock2.release()

def out_B(num):
    for i in range(num):
        lock2.acquire()
        print('B', end='')
        lock3.release()

def out_C(num):
    for i in range(num):
        lock3.acquire()
        print('C', end='')
        lock4.release()

def out_D(num):
    for i in range(num):
        lock4.acquire()
        print('D', end='')
        lock1.release()

if __name__ == "__main__":
    for line in sys.stdin:
        NUM = int(line)
        lock1 = threading.Lock()
        lock2 = threading.Lock()
        lock3 = threading.Lock()
        lock4 = threading.Lock()

        lock2.acquire()
        lock3.acquire()
        lock4.acquire()

        t1 = threading.Thread(target=out_A, args=(NUM,))
        t2 = threading.Thread(target=out_B, args=(NUM,))
        t3 = threading.Thread(target=out_C, args=(NUM,))
        t4 = threading.Thread(target=out_D, args=(NUM,))

        t1.start()
        t2.start()
        t3.start()
        t4.start()
        
        t1.join()
        t2.join()
        t3.join()
        t4.join()
        
        print()
发表于 2019-06-15 23:19:22 回复(10)
while True:
    try:
        print("ABCD"*int(input()))
    except:
        break
发表于 2017-09-08 14:02:16 回复(14)
//写的都什么鬼,明明要多线程。就用线程池加锁就可以的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        //Scanner in = new Scanner(System.in);
        ExecutorService service = Executors.newFixedThreadPool(4);
        String str;

        while((str = in.readLine()) != null) {
            int n = Integer.valueOf(str);
            for(int i = 0; i < n; i++) {
                service.execute(new MyRunnable("A", 0));
                service.execute(new MyRunnable("B", 1));
                service.execute(new MyRunnable("C", 2));
                service.execute(new MyRunnable("D", 3));
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
        service.shutdown();
    }
    static volatile int cnt = 0;
    static ReentrantLock lock = new ReentrantLock();
    static class MyRunnable implements Runnable {
        String s;
        int targetNum;

        public MyRunnable(String str, int targetNum) {
            this.s = str;
            this.targetNum = targetNum;
        }

        @Override
        public void run() {
            synchronized(lock) {
                while(cnt % 4 != targetNum) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                cnt++;
                cnt %= 4;
                System.out.print(s);
                lock.notifyAll();
            }
        }
    }
}

发表于 2021-05-06 12:37:43 回复(0)
while True:
    try:
        import threading
        # 给每个线程定义锁
        a_lock = threading.Lock()
        b_lock = threading.Lock()
        c_lock = threading.Lock()
        d_lock = threading.Lock()
        count = int(input()) * 4  # 每个字母输出n次,一个4n次输出
        def show_a():
            global count
            while count >= 4:
                a_lock.acquire()
                print("A", end="")
                b_lock.release()
                count -= 1
        def show_b():
            global count
            while count >= 3:
                b_lock.acquire()
                print("B", end="")
                c_lock.release()
                count -= 1
        def show_c():
            global count
            while count >= 2:
                c_lock.acquire()
                print("C", end="")
                d_lock.release()
                count -= 1
        def show_d():
            global count
            while count >= 1:
                d_lock.acquire()
                print("D", end="")
                a_lock.release()
                count -= 1
        thread_list = []
        func_list = [show_a, show_b, show_c, show_d]
        for func in func_list:
            thread = threading.Thread(target=func)
            thread_list.append(thread)
        # 最先输出A,其他线程暂时锁住
        b_lock.acquire()
        c_lock.acquire()
        d_lock.acquire()
        for th in thread_list:
            th.setDaemon(True)
            th.start()  # 开始线程
        for th in thread_list:
            th.join()  # 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程才终止
        # print("final count", count)
    except:
        break

这段代码在本地IDE测试还有在线自测都没有问题,为什么在提交运行的时候会出现输入22本应该输出长度为88的字符串,却输出了长度为1508的字符串呢?最后打印的count已经变为0,线程也都终止了,为什么还会出现这种情况呢?(备注:本地测试和在线自测输入22可以得到正确结果)

发表于 2020-08-02 14:51:09 回复(1)
#include <iostream>
#include <thread>
#include <mutex>
#include <string>

using namespace std;

string g_write;
mutex mtx;
bool stop = false;

void thread_fun1(int num) {
    while (num) {
        if (mtx.try_lock()) {
            int len = g_write.length();
            if (len % 4 == 0) {
                g_write += 'A';
                num--;
            }
            mtx.unlock();
        }
    }
    stop = true;
}

void thread_fun2() {
    while(1) {
        if (mtx.try_lock()) {
            int len = g_write.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 1) {
                g_write += 'B';
            }
            mtx.unlock();
        }
    }
}
void thread_fun3() {
    while(1) {
        if (mtx.try_lock()) {
            int len = g_write.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 2) {
                g_write += 'C';
            }
            mtx.unlock();
        }
    }
}
void thread_fun4() {
    while(1) {
        if (mtx.try_lock()) {
            int len = g_write.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 3) {
                g_write += 'D';
            }
            mtx.unlock();
        }
    }
}
int main () {
    int in;
    while (cin >> in) {
        thread t1(thread_fun1, in);
        thread t2(thread_fun2);
        thread t3(thread_fun3);
        thread t4(thread_fun4);
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        cout << g_write.c_str() << endl;
        g_write.clear();
        stop = false;
    }
    return 0;
}

发表于 2020-07-11 15:59:54 回复(2)
//直接输出也能通过,着实让我很意外...
import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
int num=sc.nextInt();
process(num);
}
        sc.close();
}

private static void process(int num)
{
for(int i=0;i<num;i++)
{
System.out.print("ABCD");
}
System.out.println();
}
}
发表于 2017-08-03 11:17:09 回复(4)
看不下去了,你们都不用线程池的麽。。
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Task implements Runnable{
    public String output;
    public Task(String output){
        this.output = output;
    } @Override public void run() {
        // System.out.println("give me offer.");
        System.out.print(output);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ExecutorService threadPoolhreadPol = Executors.newSingleThreadExecutor();
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            for (int i = 0; i < n; i++) {
                threadPoolhreadPol.execute(new Task("A"));
                threadPoolhreadPol.execute(new Task("B"));
                threadPoolhreadPol.execute(new Task("C"));
                threadPoolhreadPol.execute(new Task("D"));
            }
             try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
        threadPoolhreadPol.shutdown();
        scanner.close();
    }
}

编辑于 2019-08-02 13:36:27 回复(6)
# 2020年11月17日18:52:31
while True:
    try:
        n = int(input())
        print("ABCD"*n)
    except:
        break
        

发表于 2020-11-17 18:56:29 回复(2)
看了各位大佬用多线程,感觉自己弱爆了。。。这样也能ac(逃)
#include <stdio.h>
#include<iostream>  
using namespace std;

int main()
{
    int n;
    while (cin>>n)
    {
        while (n--)
            cout << "ABCD";
        cout << endl;
    }
    //system("pause");
    return 0;

}

发表于 2017-09-21 09:02:22 回复(2)