首页 > 试题广场 >

多线程

[编程题]多线程
  • 热度指数: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.util.*;
import java.util.concurrent.Semaphore;
public class Main{
    private static Semaphore a = new Semaphore(1);
    private static Semaphore b = new Semaphore(0);
    private static Semaphore c = new Semaphore(0);
    private static Semaphore d = new Semaphore(0);
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
        int n = sc.nextInt();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                int count = n;
                while(count > 0){
                    try {
                        a.acquire();
                        System.out.print("A");
                        b.release();
                        count--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                int count = n;
                while(count > 0){
                    try {
                        b.acquire();
                        System.out.print("B");
                        c.release();
                        count--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Runnable r3 = new Runnable() {
            @Override
            public void run() {
                int count = n;
                while(count > 0){
                    try {
                        c.acquire();
                        System.out.print("C");
                        d.release();
                        count--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Runnable r4 = new Runnable() {
            @Override
            public void run() {
                int count = n;
                while(count > 0){
                    try {
                        d.acquire();
                        System.out.print("D");
                        a.release();
                        count--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new Thread(r1).start();
        new Thread(r2).start();
        new Thread(r3).start();
        new Thread(r4).start();
        }
    }
}

发表于 2021-08-30 01:28:22 回复(0)
使用Semaphore信号量保证按顺序执行每个线程;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        char[] ans;
        Thread[] threads = new Thread[4];
        for(int i=0;i<4;i++){
            threads[i]  = new Thread(new printer((char)('A'+i)));
        }
        Semaphore a = new Semaphore(1);//4个信号量,保证按顺序执行。
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);
        Semaphore d = new Semaphore(0);
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            while(n-->0){
                try {
                    a.acquire();
                    threads[0].run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                b.release();
                try {
                    b.acquire();
                    threads[1].run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                c.release();
                try {
                    c.acquire();
                    threads[2].run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                d.release();
                try {
                    d.acquire();
                    threads[3].run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a.release();
            }
            System.out.println("");
        }
    }
}
class printer implements Runnable{
    private char output;
    public printer(){}
    public printer(char output){
        this.output = output;
    }

    @Override
    public void run() {
        System.out.print(output);
    }
}


发表于 2021-08-06 22:27:49 回复(2)
import java.util.*;
import java.util.concurrent.locks.*;


//1.注意导包
//2.多行输入,sleep(100)
class shareResource{
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();
    Condition c4 = lock.newCondition();
    
    public void printA()throws InterruptedException{
        lock.lock();
        try{
            while(flag != 1){
                c1.await();
            }
            System.out.print("A");
            flag = 2;
            c2.signal();
        }finally{
            lock.unlock();
        }
    }
    
    public void printB()throws InterruptedException{
        lock.lock();
        try{
            while(flag != 2){
                c2.await();
            }
            System.out.print("B");
            flag = 3;
            c3.signal();
        }finally{
            lock.unlock();
        }
    }
    
    
    public void printC()throws InterruptedException{
        lock.lock();
        try{
            while(flag != 3){
                c3.await();
            }
            System.out.print("C");
            flag = 4;
            c4.signal();
        }finally{
            lock.unlock();
        }
    }
    
    
    public void printD()throws InterruptedException{
        lock.lock();
        try{
            while(flag != 4){
                c4.await();
            }
            System.out.print("D");
            flag = 1;
            c1.signal();
        }finally{
            lock.unlock();
        }
    }
    
}

//线程的定制化通信
//用juc包中的await()和signal()完成
public class Main{
    public static void main(String[] args)throws Exception{
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            int amount = scan.nextInt();
            shareResource share = new shareResource();
            new Thread(new Runnable(){
                @Override
                public void run(){
                    for(int i=0;i<amount;i++){
                        try{
                            share.printA();    
                        }catch(Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            },"AA").start();

            new Thread(new Runnable(){
                @Override
                public void run(){
                    for(int i=0;i<amount;i++){
                        try{
                            share.printB();    
                        }catch(Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            },"BB").start();

            new Thread(new Runnable(){
                @Override
                public void run(){
                    for(int i=0;i<amount;i++){
                        try{
                            share.printC();    
                        }catch(Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            },"CC").start();

            new Thread(new Runnable(){
                @Override
                public void run(){
                    for(int i=0;i<amount;i++){
                        try{
                            share.printD();    
                        }catch(Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            },"DD").start();
            
            Thread.sleep(100);
            System.out.println();
        }
    }
    
}

发表于 2021-08-05 18:32:50 回复(0)
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int intPut = Integer.parseInt(scanner.nextLine());
            Character[] answerArray = new Character[intPut * 4];

            Thread[] threads = new Thread[4];
            char[] chars = new char[]{'A','B','C','D'};

            for (int i = 0; i < 4; i++) {
                threads[i] = new Thread(new Printer(answerArray, chars[i]));
                threads[i].start();
            }

            for (int i = 0; i < 4; i++) threads[i].join();

            for (Character c : answerArray) System.out.print(c);
            System.out.print("\n");
        }
    }
}


class Printer implements Runnable {
    private final Character ch;
    private final Character[] answerArray;

    Printer(Character[] answerArray, Character ch) {
        this.answerArray = answerArray;
        this.ch = ch;
    }

    @Override
    public void run() {
        int cnt = ch - 'A';
        while (cnt < answerArray.length) {
            answerArray[cnt] = ch;
            cnt += 4;
        }
    }
}


开四个线程然后join一下就完事儿了
发表于 2021-08-01 11:55:08 回复(1)
//贼慢贼消耗资源的写法
import java.util.Scanner;
public class Main{
    volatile static int flag = 1;
    static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Scanner sc =new Scanner(System.in);
        while(sc.hasNext()){
            int l = sc.nextInt();
            //int Thread_num = 4;
            Thread ThreadA;
            Thread ThreadB;
            Thread ThreadC;
            Thread ThreadD;

            for (int i = 0; i < l; i++) {
                ThreadA = cerateThread('A',1);
                ThreadB = cerateThread('B',2);
                ThreadC = cerateThread('C',3);
                ThreadD = cerateThread('D',4);
                ThreadA.start();
                ThreadA.join();
                ThreadB.start();
                ThreadB.join();
                ThreadC.start();
                ThreadC.join();
                ThreadD.start();
                ThreadD.join();
            }
            System.out.println();
        }
    }
    private static Thread cerateThread(char c, int f){
        return new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object){
                    while(flag!=f){
                        try {
                            object.notifyAll();
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(c);
                    flag = f%4+1;
                }
            }
        });
    }
}
发表于 2021-07-05 17:22:27 回复(0)

比较坑的一点在于,该题是多组输入。

可能存在主线程读取完输入数据,创建出4各线程开始工作后,立即又读取下一组输入,又创建出了4个线程,导致它们出现同时输出的情况。所以主线程的数据读取,与子线程也需要保持同步。

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

public class Main {

    Semaphore read = new Semaphore(1);

    public static void main(String[] args) {
        Main s = new Main();
        s.doo();

    }

    public void doo() {

        Scanner scanner = new Scanner(System.in);

        try {
            while(scanner.hasNext()) {
                read.acquire();
                int n = scanner.nextInt();
                if (n<0) break;
                this.solution(n);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    public void solution(int n) {

        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);
        Semaphore d = new Semaphore(0);

        // Print A
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    a.acquire();
                    System.out.print("A");
                    b.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Print B
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    b.acquire();
                    System.out.print("B");
                    c.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Print C
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    c.acquire();
                    System.out.print("C");
                    d.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Print D
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    d.acquire();
                    System.out.print("D");
                    a.release();
                }
                System.out.println();
                read.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
发表于 2021-07-03 23:43:26 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] args) throws IOException, InterruptedException
    {
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
        String str;
        while((str=bf.readLine())!=null){
            int n=Integer.parseInt(str);
            final Object a=new Object();
            final StringBuffer s=new StringBuffer("");

            Thread t1=new Thread(){
                @Override
                public void run()
                {
                    s.append("A");
                }
            };
            t1.start();
            t1.join();
            Thread t2=new Thread(){
                @Override
                public void run()
                {
                    s.append("B");

                }
            };
            t2.start();
            t2.join();
            Thread t3=new Thread(){
                @Override
                public void run()
                {
                    s.append("C");

                }
            };
            t3.start();
            t3.join();
            Thread t4=new Thread(){
                @Override
                public void run()
                {
                    s.append("D");
                }
            };
            t4.start();
            t4.join();

            for(int i=0;i<n-1;i++){
                t1.run();
                t2.run();
                t3.run();
                t4.run();
            }

            System.out.println(s);

        }
    }


} 
编辑于 2021-05-22 19:29:37 回复(0)
//写的都什么鬼,明明要多线程。就用线程池加锁就可以的。

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)
写那么复杂干嘛,直接如下:
package thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;

public class ThreadTest
{
    private static char[] arr = new char[3000];
    private static int index = 0;

    static Thread t1 = null;
    static Thread t2 = null;
    static Thread t3 = null;
    static Thread t4 = null;

    private synchronized static void addValue(char value){
        arr[index] = value;
        index++;
    }

    private static String printArr(){
        for(char c : arr){
            System.out.print(c);
        }
        return "";
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int times = sc.nextInt();
        CountDownLatch count = new CountDownLatch(times);

        t1 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                for(int i =0;i<times;i++){
                    addValue('A');
                    //index++;
                    LockSupport.unpark(t2);
                    LockSupport.park();//暂停

                }

            }
        });

        t2 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                for(int i =0;i<times;i++){
                    LockSupport.park();//暂停
                    addValue('B');
                    //index++;
                    LockSupport.unpark(t3);

                }
            }
        });

        t3 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                for(int i =0;i<times;i++){
                    LockSupport.park();//暂停
                    addValue('C');
                    //index++;
                    LockSupport.unpark(t4);


                }
            }
        });

        t4 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                for(int i =0;i<times;i++){
                    LockSupport.park();//暂停
                    addValue('D');
                    //index++;
                    count.countDown();//计数器减一
                    LockSupport.unpark(t1);


                }
            }
        });
        t1.setPriority(10);
        t1.start();
        t2.start();
        t3.start();
        t4.start();

        try
        {
            count.await();
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printArr();
    }

}



发表于 2021-04-08 14:18:36 回复(0)


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.print(output);
    }
}
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        while(sc.hasNext()) {
            int m = sc.nextInt();
            for(int i=0;i<m;i++) {
                threadPool.execute(new Task("A"));
                threadPool.execute(new Task("B"));
                threadPool.execute(new Task("C"));
                threadPool.execute(new Task("D"));
            }
            try {
                Thread.sleep(100);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
        threadPool.shutdown();        

    }

}

发表于 2021-03-15 14:56:45 回复(0)
import java.util.*;
public class Main{
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        Object d = new Object();

        Thread at = new AThread(count,b,a);
        Thread bt = new BThread(count,c,b);
        Thread ct = new CThread(count,d,c);
        Thread dt = new DThread(count,a,d);

        bt.start();ct.start();dt.start();at.start();
        try {
            dt.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
    }

    static class AThread extends Thread{

        private int count ;
        private Object next;
        private Object self;
        private boolean isFirstRun = true;
        public AThread(int count,Object next,Object self){
            this.count=count;
            this.next = next;
            this.self = self;
        }
        public void run(){
            for(int i=0;i<count;i++){
                try{
                    synchronized (self) {
                        if (!isFirstRun) {
                            self.wait();
                        }
                        isFirstRun = false;
                        sb.append("A");

                    }
                    synchronized (next) {
                        next.notify();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    static class BThread extends Thread{

        private int count ;
        private Object next;
        private Object self;
        public BThread(int count,Object next,Object self){
            this.count=count;
            this.next = next;
            this.self = self;
        }
        public void run(){
            for(int i=0;i<count;i++){
                try{
                    synchronized (self) {
                        self.wait();
                        sb.append("B");
                    }
                    synchronized (next) {
                        next.notify();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    static class CThread extends Thread{

        private int count ;
        private Object next;
        private Object self;
        public CThread(int count,Object next,Object self){
            this.count=count;
            this.next = next;
            this.self = self;
        }
        public void run(){
            for(int i=0;i<count;i++){
                try{
                    synchronized (self) {
                        self.wait();
                        sb.append("C");
                    }
                    synchronized (next) {
                        next.notify();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    static class DThread extends Thread{

        private int count ;
        private Object next;
        private Object self;
        public DThread(int count,Object next,Object self){
            this.count=count;
            this.next = next;
            this.self = self;
        }
        public void run(){
            for(int i=0;i<count;i++){
                try{
                    synchronized (self) {
                        self.wait();
                        sb.append("D");
                    }
                    synchronized (next) {
                        next.notify();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
发表于 2021-03-14 21:49:57 回复(0)
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.*;
public class Main{
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        Object A = new Object();
        Object B = new Object();
        Object C = new Object();
        Object D = new Object();
        ExecutorService executor = Executors.newCachedThreadPool();
        while((input = br.readLine()) != null) {
            int num = Integer.parseInt(input);
            executor.submit(new PrintStr(D, A, "A", num));
            Thread.sleep(1);
            executor.submit(new PrintStr(A, B, "B", num));
            Thread.sleep(1);
            executor.submit(new PrintStr(B, C, "C", num));
            Thread.sleep(1);
            Future<Integer> future = executor.submit(new PrintStr(C, D, "D", num));
            Thread.sleep(1);
            Integer f = future.get();
            if(f == 0) {
                System.out.println();
            }
        }
        executor.shutdown();
    }
}
    /**
     * 任务类
     */
    class PrintStr implements Callable {
        // 上个线程锁
        public Object pre;
        // 当前线程锁
        public Object self;
        // 当前要打印的字符
        public String name;
        // 打印次数
        public Integer times;
        
        public PrintStr(Object pre, Object self, String name, Integer times) {
            this.pre = pre;
            this.self = self;
            this.name = name;
            this.times = times;
        }
        
        @Override
        public Integer call() {
            // 多线程while约束线程执行次序
            while(times > 0) {
                synchronized (pre) {
                    synchronized (self) {
                        System.out.print(name);
                        times--;
                        self.notifyAll();
                    }
                    try {
                        if (times == 0) pre.notifyAll();
                        else pre.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return times;
        }
    }
发表于 2021-02-19 12:28:11 回复(0)
/**
 * 
 */

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

/**
 * @author NI
 * @since 2021年2月18日-下午3:30:30
 */
public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> numbers = new ArrayList<Integer>();
        while (scanner.hasNextInt()) {
            numbers.add(scanner.nextInt());
        }
        Semaphore semaphore = new Semaphore(1);
        Thread thread1 = new Thread(() -> {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print("A");
            semaphore.release();
        }, "thread1");
        Thread thread2 = new Thread(() -> {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print("B");
            semaphore.release();
        }, "thread2");
        Thread thread3 = new Thread(() -> {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print("C");
            semaphore.release();
        }, "thread3");
        Thread thread4 = new Thread(() -> {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print("D");
            semaphore.release();
        }, "thread4");

        numbers.forEach(num -> {
            for (; num > 0; num--) {
                thread1.run();
                thread2.run();
                thread3.run();
                thread4.run();
            }
            System.out.println();
        });

        scanner.close();
    }

}


信号量控制只有一个线程运行,在秒杀系统中可以用到

发表于 2021-02-18 17:07:12 回复(0)
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) throws InterruptedException {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int len = sc.nextInt();
            Conditions c = new Conditions(len);
            Thread t1 = new Thread(()->{
                for(int i=0;i<len;i++){
                    c.conditionAddA();
                }
            },"A");
            t1.start();
            Thread t2 = new Thread(c::conditionAddB,"B");
            t2.start();
            Thread t3 = new Thread(c::conditionAddC,"C");
            t3.start();
            Thread t4 = new Thread(c::conditionAddD,"D");
            t4.start();
            t4.join();
            c.printArr();
        }
    }
}
class Conditions{
    private final String[] strArr;
    private final Lock lock ;
    private final Condition a ;
    private final Condition b;
    private final Condition c ;
    private final Condition d ;
    private String state ;

    Conditions(int len){
        this.strArr = new String[4*len];
        lock = new ReentrantLock();
        a = lock.newCondition();
        b = lock.newCondition();
        c = lock.newCondition();
        d = lock.newCondition();
        state = "A";
    }

    void conditionAddA(){
            lock.lock();
            try {
                while (!state.equals("A")){
                    a.await();
                }
                //System.out.println("a get await");
                for(int i = 0; i<strArr.length; i= i+4){
                    if(strArr[i] == null){
                        strArr[i] = "A";
                        break;
                    }
                }
                state="B";
                b.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
    }
    void conditionAddB(){
        while(strArr[strArr.length-3]==null){
            lock.lock();
            try {
                while (!state.equals("B")){
                    b.await();
                }
                for(int i = 1; i<strArr.length; i=i+4){
                    if(strArr[i] == null){
                        strArr[i] = "B";
                        break;
                    }
                }
                state="C";
                c.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    void conditionAddC(){
        while(strArr[strArr.length-2]==null){
            lock.lock();
            try {
                while (!state.equals("C")){
                    c.await();
                }
                for(int i = 2; i<strArr.length; i= i+4){
                    if(strArr[i] == null){
                        strArr[i] = "C";
                        break;
                    }
                }
                state="D";
                d.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    void conditionAddD(){
        while(strArr[strArr.length-1]==null){
            lock.lock();
            try {
                while (!state.equals("D")){
                    d.await();
                }
                for(int i = 3; i<strArr.length; i=i+4){
                    if(strArr[i] == null){
                        strArr[i] = "D";
                        break;
                    }
                }
                state = "A";
                a.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    void printArr(){
        for(String s : strArr){
            System.out.print(s);
        }
        System.out.println();
    }
}


发表于 2021-01-29 10:32:44 回复(0)
package com.juc.leetCode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;

/**
 * LockSupport + CountDownLatch
 *
 * @author : z_sz
 * @date : 2020/12/29 22:46
 */
public class Demo23 {
    static Thread a = null, b = null, c = null,d = null;
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        if((str = bufferedReader.readLine()) != null) {
            int times = Integer.parseInt(str);
            for (int i = 0; i < times; i++) {
                CountDownLatch latch = new CountDownLatch(4);
                a = new Thread(()->{
                    System.out.print("A");
                    LockSupport.unpark(b);
                    latch.countDown();
                });
                b = new Thread(()->{
                    LockSupport.park();
                    System.out.print("B");
                    LockSupport.unpark(c);
                    latch.countDown();
                });
                c = new Thread(()->{
                    LockSupport.park();
                    System.out.print("C");
                    LockSupport.unpark(d);
                    latch.countDown();
                });
                d = new Thread(()->{
                    LockSupport.park();
                    System.out.print("D");
                    latch.countDown();
                });
                a.start();b.start();c.start();d.start();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
本地运行没问题,这里无法通过

发表于 2020-12-29 23:51:08 回复(0)
public class Main {

    static final java.util.Scanner SC = new java.util.Scanner(System.in);

    public static void main(String... args) {
        while (SC.hasNextInt()) {
            int n = SC.nextInt();
            CharArray array = new CharArray(n);
            Thread athread = startThread(array, n, 'A');
            Thread bthread = startThread(array, n, 'B');
            Thread cthread = startThread(array, n, 'C');
            Thread dthread = startThread(array, n, 'D');
            try {
                athread.join();
                bthread.join();
                cthread.join();
                dthread.join();
            } catch (InterruptedException e) {
            }
            System.out.println(array.toString());
        }
    }

    static Thread startThread(final CharArray array, final int n, final char target) {
        Thread thread = new Thread() {
            public void run() {
                for (int i = 0; i < n; i++) {
                    array.write(target);
                }
            }
        };
        thread.start();
        return thread;
    }

    static class CharArray {

        final char[] array;
        volatile int cursor;

        /**
         * 
         */
        CharArray(int n) {
            super();
            array = new char[n << 2];
            cursor = 0;
        }

        void write(char target) {
            while (true) {
                if (checkWritable(target)) {
                    cursor++;
                    array[cursor - 1] = target;
                    break;
                } else {
                    Thread.yield();
                }
            }
        }

        private boolean checkWritable(char target) {
            if (cursor == 0) {
                if (target == 'A') {
                    return true;
                } else {
                    return false;
                }
            } else {
                char last = array[cursor - 1];
                if ((target == 'A' && last == 'D') || target - last == 1) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        @Override
        public String toString() {
            return new String(array, 0, cursor);
        }

    }

}

发表于 2020-11-11 22:19:36 回复(0)
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    private final static int THREAD_NUM = 4;
    private static char[] chs = new char[1032*THREAD_NUM];
    private static int index = 0;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            final AtomicInteger lock = new AtomicInteger((n+1)*THREAD_NUM);
            InnerThread t1 = new InnerThread('A', 0, lock,n);
            InnerThread t2 = new InnerThread('B', 3, lock,n);
            InnerThread t3 = new InnerThread('C', 2, lock,n);
            InnerThread t4 = new InnerThread('D', 1, lock,n);
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            try {
                t1.join();
                t2.join();
                t3.join();
                t4.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(new String(chs).substring(0, n*THREAD_NUM));
        }
        sc.close();
    }

    //内部线程类
    private static class InnerThread extends Thread{
        private char ch;
        private int num;
        private AtomicInteger lock;
        private int count;
        public InnerThread(char ch, int num, AtomicInteger lock, int count){
            this.ch = ch;
            this.num = num;
            this.lock=lock;
            this.count=count;
        }

        @Override
        public void run() {
            for (int i = 0; i <count ; i++) {
                while(lock.get()%4!=num){
                    try {
                        sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } 
                }
                synchronized(lock) {
                    chs[index]=ch;
                    index++;
                    lock.getAndDecrement();
                }
            }
        }
    }
}
发表于 2020-09-11 11:34:40 回复(0)
import java.util.*;

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


        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {

            int n = in.nextInt();
            for (int i = 0; i < n; i++) {
                printStr();
            }
            System.out.println();
        }

    }

    public static void printStr() throws InterruptedException {

        Thread t1 = new Thread(() -> System.out.print("A"));
        Thread t2 = new Thread(() -> System.out.print("B"));
        Thread t3 = new Thread(() -> System.out.print("C"));
        Thread t4 = new Thread(() -> System.out.print("D"));

        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
        t3.join();
        t4.start();
        t4.join();
    }
}

发表于 2020-08-19 22:41:26 回复(0)

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        while(s.hasNext()){
            int n = s.nextInt();
            System.out.println(Thread1(n));
        }
    }
    public static String Thread1(int num){
        String str="";
        for(int i=0;i<num;i++){
            str+="ABCD";
        }
        return str;
    }
}


发表于 2020-07-27 22:03:02 回复(0)

问题信息

难度:
36条回答 59002浏览

热门推荐

通过挑战的用户