简介

多线程的同步是所有的公司都会使用的. 先将各种语言的放上来

code

#include <iostream>
#include <thread>
#include <mutex>
#include <string>

using namespace std;

string g;
mutex mtx;
bool stop = false;

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


void thread_fun2() {
    while(1) {
        if(mtx.try_lock()) {
            int len = g.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 1) {
                g += 'B';
            }
            mtx.unlock();
        }
    }
}

void thread_fun3() {
    while(1) {
        if (mtx.try_lock()) {
            int len = g.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 2) {
                g += 'C';
            }
            mtx.unlock();
        }
    }
}

void thread_fun4() {
    while(1) {
        if (mtx.try_lock()) {
            int len = g.length();
            if (stop && len % 4 == 0) {
                mtx.unlock();
                return;
            }
            if (len % 4 == 3) {
                g += '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.c_str() << endl;
        g.clear();
        stop = false;
    }
    return 0;
}

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()
//借助于线程可见性变量,以及线程基本应用,完美AC
import java.util.*;
public class demo{
    public static volatile int count=0;//线程可见性变量
    public static char []buff=new char[1024*4];
    public static int index=0;
    public static  int times=10;//执行次数
    public static class CountThread extends Thread{
        public int mycount=0;
        public char ch=' ';
        public CountThread(int mycount,char ch){
            this.mycount=mycount;
            this.ch=ch;
        }
        @Override
        public void run() {
            for(int i=0;i<=times;i++){
                while(mycount!=count){
                    //自旋等待执行,不需要阻塞
                }
                buff[index]=ch;//放入缓存区
                index++;
                count=(count+1)%4;//切换到下一个线程执行
            }
        }
    }
    public static void main(String[] arg) throws Exception{
        Scanner s=new Scanner(System.in);
        while(s.hasNext()){
            index=0;//设置缓冲区索引
            count=0;
            times=s.nextInt();
            CountThread a1=new CountThread(0,'A');
            CountThread a2=new CountThread(1,'B');
            CountThread a3=new CountThread(2,'C');
            CountThread a4=new CountThread(3,'D');
            a1.start();
            a2.start();
            a3.start();
            a4.start();
            a1.join();
            a2.join();
            a3.join();
            a4.join();
            for(int i=0;i<times*4;i++)
                System.out.print(buff[i]);
            System.out.println();
        }
    }
}
//写的都什么鬼,明明要多线程。就用线程池加锁就可以的。
 
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();
            }
        }
    }
}
posted on 2021-06-27 18:36  HDU李少帅  阅读(80)  评论(0编辑  收藏  举报