- Single Threaded Executio
-
Only one thread is allowed to consume resources at a time.
-
Multithreading shares a resource that allows access to resources only from threads that have access to the resource lock, avoiding the conflict of multi-threaded access to resources.
- Applicable environment
- Sample Example
-
Rob Chair: Kindergarten teachers organize 3 children to rob a chair, the rule is a person can only occupy a chair, the chair is accounted for, the teacher announced the results, the current possession of the children left, re-start preemption.
-
Exclusive resources: chair, teacher.
-
Threads: 3 children.
- Teacher Class
-
Package Singlethreadedexecution;public class Teacher {public void chairholded (String owner) {if (owner!=null) { System.out.println (owner+ "grabbed the chair! ");}} public static void Main (string[] args) {Teacher t=new Teacher (); Ichair chair=new Chair (t);//single-threaded operation mode, grab chair. 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 ();}}
- Kids Class
-
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;} @Overridepublic void Run () {while (true) {Boolean issuccess=chair.setowner (this.myname); if (issuccess) {cnt++;} try {thread.sleep (1);} catch (Interruptedexception e) {System.out.println ("interrupted!");}}}
- Chair interface
-
-
Package Singlethreadedexecution;public Interface Ichair {public boolean setowner (String newone);}
- Chair class
-
Package Singlethreadedexecution;public class Chair implements Ichair{private Teacher observer=null;private String Owner ;p ublic Chair (Teacher observer) {This.observer=observer;} Public synchronized Boolean SetOwner (String newone) {this.owner=newone;observer.chairholded (This.owner); return true;}}
This article is from the Java Technology Stack notes blog, so be sure to keep this source http://stroll.blog.51cto.com/11038467/1855015
Java multithreaded (three) mode-single threaded execution