这是道面试题目:有三个线程分别打印A、B、C,请用多线程编程实现,在屏幕上循环打印10次ABCABC…
见代码:
#include <iostream>
#include <Windows.h> using namespace std; HANDLE hMutex;
int counts = ;
int flag = ; void t1();
void t2();
void t3(); int main() {
HANDLE hThread = CreateThread(NULL, , (LPTHREAD_START_ROUTINE)t1, NULL, , NULL);
hThread = CreateThread(NULL, , (LPTHREAD_START_ROUTINE)t2, NULL, , NULL);
hThread = CreateThread(NULL, , (LPTHREAD_START_ROUTINE)t3, NULL, , NULL);
hMutex = CreateMutex(NULL, FALSE, L"lvhuan");
CloseHandle(hThread);
while(counts<){
Sleep();
}
return ;
}
void t1() {
while (counts < ) {
WaitForSingleObject(hMutex, INFINITE);
if (flag == ) {
flag = ;
cout << 'A' << endl;
counts++;
}
ReleaseMutex(hMutex);
}
}
void t2() {
while (counts < ) {
WaitForSingleObject(hMutex, INFINITE);
if (flag == ) {
flag = ;
cout << 'B' << endl;
counts++;
}
ReleaseMutex(hMutex);
}
}
void t3() {
while (counts < ) {
WaitForSingleObject(hMutex, INFINITE);
if (flag == ) {
flag = ;
cout << 'C' << endl;
counts++;
}
ReleaseMutex(hMutex);
}
}
这里给个java版本的链接:http://mouselearnjava.iteye.com/blog/1949228?utm_source=tuicool&utm_medium=referral