synchronized (o1) {
try {
Thread.sleep(1)
} catch (InterruptedException e) {
e.printStackTrace()
}
synchronized (o2) {
System.out.println("1")
}
}
#include <windows.h>#include <iostream>
#include<time.h>
const unsigned short SIZE_OF_BUFFER = 1//缓冲区长度
int g_buffer[SIZE_OF_BUFFER]
bool g_continue = true//控制程序结束
HANDLE g_hMutex//用于线程间的互斥
DWORD WINAPI FatherProc(LPVOID)//父进程线程
DWORD WINAPI SonProc(LPVOID)//使用打印机的线程
int main()
{
//创建各个互斥信号
g_hMutex = CreateMutex(NULL,FALSE,NULL)
const unsigned short FATHERS_COUNTS = 1//父进程线程的个数
const unsigned short SONS_COUNT = 2//使用打印机的线程的个数
//总的线程数
const unsigned short THREADS_COUNT = FATHERS_COUNTS+SONS_COUNT
HANDLE hThreads[THREADS_COUNT]//各线程的handle
DWORD fatherID[FATHERS_COUNTS]//父进程线程的标识符
DWORD sonID[SONS_COUNT]//使用打印机的线程的标识符
//父进程线程
for (int i=0i<FATHERS_COUNTS++i){
hThreads[i]=CreateThread(NULL,0,FatherProc,NULL,0,&fatherID[i])
if (hThreads[i]==NULL) return -1
}
//使用打印机的线程
for (i=0i<SONS_COUNT++i){
hThreads[SONS_COUNT+i]=CreateThread(NULL,0,SonProc,NULL,0,&sonID[i])
if (hThreads[i]==NULL) return -1
}
while(g_continue){
if(getchar())
{ //按回车后终止程序运行
g_continue = false
}
}
return 0
}
//分配打印机
void Append()
{
srand((unsigned)time(0))
std::cerr <<"打印机空闲 ...\n"
if(rand()%2)
{
g_buffer[0]=1//给PA
}
else
{
g_buffer[0]=0//给PB
}
}
//son使用打印机
void Take()
{
if(g_buffer[0]==1)
{
std::cerr <<"PA使用打印机 ... "
std::cerr <<"成功" <<std::endl<<std::endl
}
if(g_buffer[0]==0)
{
std::cerr <<"PB使用打印机 ... "
std::cerr <<"成功" <<std::endl<<std::endl
}
g_buffer[0]=-1
}
//父进程
DWORD WINAPI FatherProc(LPVOID lpPara)
{
while(g_continue){
WaitForSingleObject(g_hMutex,INFINITE)
Append()
Sleep(1500)
ReleaseMutex(g_hMutex)
}
return 0
}
//子进程
DWORD WINAPI SonProc(LPVOID lpPara)
{
while(g_continue){
WaitForSingleObject(g_hMutex,INFINITE)
Take()
Sleep(1500)
ReleaseMutex(g_hMutex)
}
return 0
} 最后的要求自己添加
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)