Java concurrent programming (1) ---- particle Applet

Source: Internet
Author: User
Particle

The class applet defines a completely hypothetical model for moving objects. Each particle is represented by its (x, y) position. At the same time, each particle includes a method to freely move its own location and a method to draw itself (a small square) through a given java. AWT. graphics object.

Although a particle object does not contain any concurrent operations, its method may be called by multiple concurrent operations. When one operation is executing a move operation and almost the other operation is calling the draw method, we need to ensure that the draw method depicts the exact position of the particle. Here, we require that the draw method be able to draw with the current position of the particle before or after the move method is called. For example, when the draw operation draws an example image using the Y value before the move method call and the X value after the move method call, a conceptual error is generated. If we allow this to happen, the draw method may be that a particle is drawn at a position that has never appeared.

We can prevent this by using the synchornized keyword. Synchronized can modify a method or a code block. Every instance of the object is locked before it enters a synchronous method, and the lock is automatically released when it leaves the method. The operation on the code block is the same, but the synchronization code block requires a parameter to lock the object. The most common parameter is this, which means to lock the object of the method currently being executed. When a thread holds a lock, other threads must be blocked and wait for the thread to properly remove the lock. Locking does not work for non-synchronous methods. Therefore, this non-synchronous method can be executed even if another thread has this lock.

import java.awt.Graphics;import java.util.Random;public class Particle {protected int x;protected int y;protected final Random rng=new Random();public Particle(int initialX,int initialY){x=initialX;y=initialY;}public synchronized void move(){x+=rng.nextInt(10)-5;y+=rng.nextInt(10)-10;}@SuppressWarnings("unused")public void draw(Graphics g){int lx,ly;synchronized (this) {lx=x;ly=y;}g.drawRect(lx, lx, 10,10);}}

In the above Code, we use the final keyword to modify the random number generator RNG, so as to ensure that the reference of this member variable will not be changed. In this way, it will not be affected by our locking rules. Many concurrent programs use a large number of final keywords to help Automatically highlight the design intent needed to reduce synchronization in the document.

The draw method needs to get a pair of consistent x and y values at the same time. Since a method can return only one value at a time, but we need to obtain both x and y values here, we cannot simply encapsulate the access to variables in a synchronous method. Instead, we use the same Code Synchronization block.

We can see that the draw method follows the important rule we mentioned above and releases the lock when calling the method on other objects (this method is G. drawrect ). The move method seems to be against our rules. It calls the RNG. nextint method. Here, however, we do this because every particle contains its own RNG object, so the RNG object is part of the particle, therefore, it should not be regarded as the "Other Object" described in the rule ".

Participant canvas

The special canvas is a simple self-ray of Java. AWT. canvas that provides a painting area for all particles. Its main function is to call the draw method of all particles when the paint method is called.

However, the particle canvas itself is not responsible for creating and managing these particles. You can obtain these particle objects passively or actively. Here I select the passive method.

The instance variable participant is an array that stores existing particle objects. This variable is set by the Applet as needed and used by the paint method. We also applied the default rules and used two simple, synchronous get and set methods to access the participant variable, avoiding direct access to the participant itself. To simplify the program so that it can be used correctly, this participant variable cannot be set to null, but is initialized as an empty array.

Import Java. AWT. canvas; import Java. AWT. dimension; import Java. AWT. graphics; public class participant canvas extends canvas {Private Static final long serialversionuid = 1l; private particle [] participant = new particle [0]; Public Participant canvas (INT size) {setsize (new dimension (size, size);} // protected synchronized void setparticipant (particle [] PS) {If (PS = NULL) will be called by the Applet) throw new illegalargumentexception ("canno Tproceed set null! "); Participant = Ps;} protected particle [] getparticipant () {return participant;}/*** override the paint */Public void paint (Graphics g) in the canvas) {particle [] PS = getparticipant (); For (INT I = 0; I <ps. length; I ++) pS [I]. draw (g );}}
Particle Applet

Class particle and particle canvas can be used as the basis of several other programs. However, what we need to do for the particle applet is to make every example move in an autonomous "continuous" manner and update and display the positions of these examples.

Each thread instance maintains the control status required to execute and manage the call sequences that constitute its actions. The most common constructors of the thread class accept a runnable object as its parameter, when the thread is started, the runnable object's run method is called. Since both humans and classes can implement the runnable interface, it is usually convenient to use a runnable as an anonymous internal class.

Import Java. applet. applet; public class particle applet extends applet {/*****/Private Static final long serialversionuid = 1l; protected thread [] threads = NULL; // when not running, the default value is protected final participant canvas = new participant canvas (100); Public void Init () {Add (canvas);} protected thread makethread (final particle P) {runnable runloop = new runnable () {@ overridepublic void run () {// todo auto-generated Method Stubtry {for (;) {P. move (); canvas. repaint (); thread. sleep (100) ;}} catch (interruptedexception e) {// todo: handle exceptionreturn ;}}; return New thread (runloop);} public synchronized void start () {int n = 10; // If (threads = NULL) {particle [] participant = new particle [N]; for (INT I = 0; I <N; ++ I) Participant [I] = new particle (50, 50); canvas. setparticipant (participant); threads = new thread [N]; for (INT I = 0; I <n; ++ I) {threads [I] = m Akethread (participant [I]); threads [I]. Start () ;}} public synchronized void stop () {If (threads! = NULL) {for (INT I = 0; I <threads. length; I ++) threads [I]. Interrupt (); threads = NULL ;}}}

 

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.