華為機試題 多執行緒
阿新 • • 發佈:2021-06-27
簡介
多執行緒的同步是所有的公司都會使用的. 先將各種語言的放上來
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();
}
}
}
}