package huawei;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/***/
public classDemo extends Thread{private staticString tmp ;private static Lock lock = newReentrantLock();private static int state =0;staticboolean flag;public static String multiThreadWrite(final inttimes) {
tmp=newString();
flag=false;
Thread threadA=newThread()
{public voidrun(){int count =0;while(count
{lock.lock();if(state%4==0)
{
tmp+= "A";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadB=newThread()
{public voidrun(){int count =0;while(count
{lock.lock();if(state%4==1)
{
tmp+= "B";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadC=newThread()
{public voidrun(){int count=0;while(count
{lock.lock();if(state%4==2)
{
tmp+= "C";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadD=newThread()
{public voidrun()
{int count =0;while(count
{lock.lock();if(state%4==3)
{
tmp+= "D";
state++;
count++;
}lock.unlock();
}
flag=true;
}
};
threadA.start();
threadB.start();
threadC.start();
threadD.start();while(!flag); //防止main线程在四个线程执行完之前就返回tmp值
returntmp;
}
}
本文通过华为Demo示例,探讨了多线程环境下使用ReentrantLock进行同步的并发写入操作,展示了如何避免数据竞争并确保线程安全。
201

被折叠的 条评论
为什么被折叠?



