Java notes -- Application of super-Class Object multithreading + combination of internal classes and multithreading In the dining algorithm of philosophers

Source: Internet
Author: User

Java notes -- Application of super-Class Object multithreading + combination of internal classes and multithreading In the dining algorithm of philosophers
The Object class is the parent class of all Java classes. It defines three methods related to thread operations, so that all Java classes support multithreading after they are created. These three methods are: Y (), policyall (), wait (), these methods are used to control the running status of the thread. Method list: Wake y (): Wake up a single thread waiting on this object monitor notifyAll (): Wake up all threads waiting on this object monitor wait (): before calling the notify () or notifyAll () method of this object in other threads, the current thread waits for wait (long timeout): In notify () or notifyAll () the current thread waits for wait (long timeout, int nanos) before the method is called or exceeds the specified time () the current thread waits before the method is called, before the specified time is exceeded, or before other threads interrupt the current thread. -- If you want To reprint this article, please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3907610.html" thank you -- code instance: copy the code package com. xhj. thread; import java. util. random; /*** application of thread-related methods in the Object class ** @ author XIEHEJUN **/public class ObjectThreadMethod {/*** defines the maximum number of items */private int count = 10; /*** number of items in the warehouse recorded during production */private int sum = 0; private class Producter implements Runnable {@ Override public void run () {for (int I = 0; I <count; I ++) {int num = new Random (). nextInt (255); synchronized (this) {if (sum = count) {System. out. println ("the repository is full"); try {this. wait (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} else {System. out. println ("production item" + num + "Number"); this. using Y (); sum ++; System. out. println ("warehouse and Products" + sum + "pieces"); try {Thread. sleep (100);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}}} private class extends mer implements Runnable {@ Override public void run () {for (int I = 0; I <count; I ++) {synchronized (this) {if (sum = 0) {System. out. println ("warehouse is empty, please replenish"); try {this. wait (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} else {System. out. println ("Consumption I bought a product. "); this. using Y (); sum --; System. out. println ("warehouse and Products" + sum + "pieces"); try {Thread. sleep (100);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}}}/*** call the thread service */public void service () {Producter productor = new Producter (); timer mer timer mer = new timer mer (); Thread thread1 = new Thread (productor); Thread thread2 = new Thread (timer mer); thr Ead1.start (); thread2.start ();} public static void main (String [] args) {// TODO Auto-generated method stub ObjectThreadMethod ob = new ObjectThreadMethod (); ob. service () ;}} copy the code. Note: In the Object class, all the above methods are final. Do not confuse them with the Thread class. These methods must be used with the Synchronized keyword, they are all related to the object monitor. The current thread must have the monitor of this object; otherwise, an IllegalMonitorStateException occurs. Next we will combine a classic algorithm instance to deepen our understanding of the multi-threaded methods in the Object. Classic example: There are five philosophers in the dining question of philosophers. Each philosopher has a chopstick on the right hand side. Each philosopher has two states: Thinking and eating. When philosophers want to eat, they must ensure that the chopsticks in the left and right hands are available; otherwise, the philosophers enter the waiting state. If all five philosophers want to eat and are in the waiting state, a deadlock occurs in the thread. If all five philosophers are not hungry and are seriously thinking, then the thread enters the live lock (that is, the thread that is executing the thinking at this time, and the thread that eats can only wait for someone to eat) link diagram: _ thumb3_thumb we can see from the Problem description and relationship diagram, we first need to establish two link classes: chopsticks-chopsticks and philosophers-Philosopher in order to better integrate and use learned knowledge, here I will use the internal class form to complete the connection and call between the two classes. Through the above relationship diagram, we know whether chopsticks are Available or not depends on the state of philosophers and the process to be executed. Therefore, the Available of chopsticks should be designed to be synchronized. In addition, for philosophers, thinking and eating cannot be done at the same time. Either of them can only choose one, or both cannot choose, but can only wait. Therefore, the two methods thinking () and eatting () must also be synchronized. The following is a detailed code example: copy the code package com. xhj. thread; import java. util. random;/*** Dining Philosophers algorithm (internal class and multi-thread Object applications) ** @ author XIEHEJUN **/public class ChopsiticksAndPhilosophers {/*** chopsticks entity class **/private class Chopstick {/*** chopsticks Number */private int id; /*** whether chopsticks are available. The default value is available */private volatile boolean available = true; public Chopstick (int id) {this. id = id;} public int getId () {return id;} public void setAvaila Ble (boolean available) {this. available = available;} @ Override public String toString () {// TODO Auto-generated method stub return id + "Chopsticks ";}} /*** philosopher class */private class Philosopyers implements Runnable {/*** philosopher Number */private int id; /*** chopsticks object array */private Chopstick [] chopsticks;/*** philosopher state -- true indicates thinking; false indicates eating or waiting for dinner */private volatile boolean state; /*** obtain the chopsticks number on the left hand side of the philosopher *** @ return * /Private Chopstick getLeftId () {return chopsticks [id];}/*** obtain the chopsticks number on the right hand side of the philosopher ** @ return */private Chopstick getRightId () {if (id = 0) {return chopsticks [chopsticks. length-1];} else {return chopsticks [id-1];} public Philosopyers (int id, Chopstick [] chopsticks) {this. id = id; this. chopsticks = chopsticks;} @ Override public String toString () {// TODO Auto-generated method stub retu Rn id + "philosopher";}/*** philosophers are thinking */public synchronized void thinking () {if (state) {getLeftId (). setAvailable (true); getRightId (). setAvailable (true); System. out. println (id + "philosophers are thinking"); try {// think about Thread for 1 second. sleep (1000);} catch (Exception e) {e. printStackTrace () ;}} state = false;}/*** philosophers are eating */public synchronized void eating () {if (! State) {if (getLeftId (). available) {if (getRightId (). available) {getLeftId (). available = false; getRightId (). available = false; System. out. println (id + "the philosopher is eating"); try {// The time for eating for one second Thread. sleep (1000);} catch (Exception e) {e. printStackTrace () ;}} else {System. out. println ("Left" + getRightId (). getId () + "Chopsticks cannot be used" + id + "Experts enter the waiting state"); try {wait (new Random (). nextInt (100);} catch (Exception e) {e. printStackTrace () ;}} else {System. out. println ("right" + getLeftId (). getId () + "Chopsticks cannot be used" + id + "Experts enter the waiting state"); try {wait (new Random (). nextInt (100);} catch (Exception e) {e. printStackTrace () ;}} state = true ;}@ Override public void run () {// execute two philosophers to better observe the process (which can be modified as needed) for (int I = 0; I <2; I ++) {System. out. print (I + "\ t"); thinking (); eating () ;}}/ *** method of starting a service thread for a philosopher's meal */public void service () {Chopstick [] chopsticks = new Chopstick [5]; // defines the chopsticks array for (int id = 0; id <5; id ++) {chopsticks [id] = new Chopstick (id) ;}// five philosophers, start five synchronization threads for (int id = 0; id <5; id ++) {Philosopyers phers = new Philosopyers (id, chopsticks); new Thread (phers ). start () ;}} public static void main (String [] args) {ChopsiticksAndPhilosophers cap = new ChopsiticksAndPhilosophers (); cap. service ();}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.