JAVA多线程模式-Single Threaded Execution
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA多线程模式-Single Threaded Execution相关的知识,希望对你有一定的参考价值。
Single Threaded Executio
同时只允许一个线程使用资源。
多线程共享一个资源,仅允许获得了资源锁的线程对资源的访问,避免多线程访问资源造成冲突。
适用环境
多线程争用资源,资源状态(这里的状态指资源对象的属性)可被占用线程变更,需要确保各个线程所见资源状态正确的场景。
样例
抢椅子:幼儿园老师组织3个小朋友抢椅子,规则是一次只能有一个人占据椅子,椅子被占后,老师公布结果,当前占有的小朋友离开,重新开始抢占。
独占资源:椅子,老师。
线程:3个小朋友。
老师类
package SingleThreadedExecution; public class Teacher { public void chairHolded(String owner){ if(owner!=null){ System.out.println(owner+"抢到了椅子!"); } } public static void main(String[] args) { Teacher t=new Teacher(); IChair chair=new Chair(t);//单线程运行模式,抢椅子。 Child c1=new Child(chair,"c1"); Child c2=new Child(chair,"c2"); Child c3=new Child(chair,"c3"); Thread t1=new Thread(c1); Thread t2=new Thread(c2); Thread t3=new Thread(c3); t1.start(); t2.start(); t3.start(); } }
小朋友类
package SingleThreadedExecution; public class Child implements Runnable { private IChair chair=null; private String myName=null; private int cnt=0; public Child(IChair chair,String myName){ this.chair=chair; this.myName=myName; } @Override public void run() { while(true){ boolean isSuccess=chair.setOwner(this.myName); if(isSuccess){ cnt++; } try { Thread.sleep(1); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } } }
椅子接口
package SingleThreadedExecution; public interface IChair { public boolean setOwner(String newOne); }
椅子类
package SingleThreadedExecution; public class Chair implements IChair{ private Teacher observer=null; private String owner; public Chair(Teacher observer){ this.observer=observer; } public synchronized boolean setOwner(String newOne){ this.owner=newOne; observer.chairHolded(this.owner); return true; } }
本文出自 “JAVA技术栈笔记” 博客,请务必保留此出处http://stroll.blog.51cto.com/11038467/1855015
以上是关于JAVA多线程模式-Single Threaded Execution的主要内容,如果未能解决你的问题,请参考以下文章
Single Threaded Execution Pattern
nothreading use single threaded