Package tread;/*** producer consumer mode: Traffic Signal Method * Wait (): Wait, release lock; * notify (); * Wait and consumer y must be used together with sychronized; * Sleep (): Sleep With lock: **/public class movie {private string PIC; private Boolean flag = true; // signal lamp // flag = T: production, consumer waiting, notification consumption after production is complete: // flag = F: consumer consumption, producer waiting, notification production after consumption is complete; Public movie (string pic) {super (); this. PIC = PIC;} public movie () {}/ *** playback function ** @ throws interruptedexception */Public synchronized void play (strin G pic) {If (! Flag) {try {This. wait ();} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}try {thread. sleep (500);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();} This. PIC = PIC; system. out. println ("produced" + pic); this. Y (); this. flag = false;}/*** viewing function */Public synchronized void Watch () {If (FLAG) {try {This. wait ();} catch (interruptedexception e) {e. printstacktrace () ;}try {thread. sleep (200);} catch (interruptedexception e) {e. printstacktrace ();} This. Y (); this. flag = true; system. out. println ("consumed" + pic) ;}} package tread; public class player implements runnable {private movie m; @ overridepublic void run () {for (INT I = 0; I <20; I ++) {If (0 = I % 2) {M. play ("Zuo Qinglong");} else {M. play ("") ;}} public player (movie) {super (); this. M = movie ;}} package tread; public class watcher implements runnable {private movie m; @ overridepublic void run () {for (INT I = 0; I <20; I ++) {M. watch () ;}} public watcher (movie) {super (); this. M = movie ;}} package tread; public class app {public static void main (string [] ARGs) {movie M = new movie (); player P = new player (m); watcher W = New watcher (m); New thread (P ). start (); New thread (W ). start ();}}
Movie is a public resource;
The Traffic Signal Method of the production consumer mode in one of the deadlock Solutions