Java多线程实战之交叉打印的两种方法
要求效果:先打印5次“printA…”,再打印5次“printB…”,每次打印间隔1秒,重复循环20次
方式一:使用wait()和notifyAll()方法
publicclassMyService{
privatevolatilebooleanflag=false;
publicsynchronizedvoidprintA(){
try{
while(flag){
wait();
}
for(inti=0;i<5;i++){
System.out.println("printA...");
TimeUnit.SECONDS.sleep(1);
}
flag=true;
notifyAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
publicsynchronizedvoidprintB(){
try{
while(!flag){
wait();
}
for(inti=0;i<5;i++){
System.out.println("printB...");
TimeUnit.SECONDS.sleep(1);
}
flag=false;
notifyAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
publicclassBackupAimplementsRunnable{
privateMyServicemyService;
publicBackupA(MyServicemyService){
super();
this.myService=myService;
}
@Override
publicvoidrun(){
myService.printA();
}
}
publicclassBackupBimplementsRunnable{
privateMyServicemyService;
publicBackupB(MyServicemyService){
super();
this.myService=myService;
}
@Override
publicvoidrun(){
myService.printB();
}
}
publicclassRun{
publicstaticvoidmain(String[]args){
MyServicemyService=newMyService();
for(inti=0;i<20;i++){
newThread(newBackupA(myService)).start();
newThread(newBackupB(myService)).start();
}
}
}
方式二:使用await()和signalAll()方法
publicclassMyService{
privateLocklock=newReentrantLock();
privateConditioncondition=lock.newCondition();
privatebooleanflag=false;
publicvoidprintA(){
try{
lock.lock();
while(flag){
condition.await();
}
for(inti=0;i<5;i++){
System.out.println("printA...");
TimeUnit.SECONDS.sleep(1);
}
flag=true;
condition.signalAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}finally{
lock.unlock();
}
}
publicvoidprintB(){
try{
lock.lock();
while(!flag){
condition.await();
}
for(inti=0;i<5;i++){
System.out.println("printB...");
TimeUnit.SECONDS.sleep(1);
}
flag=false;
condition.signalAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
publicclassThreadAimplementsRunnable{
privateMyServicemyService;
publicThreadA(MyServicemyService){
super();
this.myService=myService;
}
@Override
publicvoidrun(){
myService.printA();
}
}
publicclassThreadBimplementsRunnable{
privateMyServicemyService;
publicThreadB(MyServicemyService){
super();
this.myService=myService;
}
@Override
publicvoidrun(){
myService.printB();
}
}
publicclassRun{
publicstaticvoidmain(String[]args){
MyServicemyService=newMyService();
for(inti=0;i<20;i++){
newThread(newThreadA(myService)).start();
newThread(newThreadB(myService)).start();
}
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接