Sixth Lecture Java Thread and Java Applet

xiaoxiao2021-03-06  62

Course index

[Thinking before class] 1. What is thread? What is the difference between it and the process? What is the direction of application? 2. How is Java thread implementation? 3. How is Java thread dispatched? 4. What is the characteristics of multi-thread in Java? How is the principle of synchronization and mutual exclusion? 5. What is the Java Applet, what is the difference between Application? 6. How to create a Java applet? 7. What is the life cycle and main method of applet? 8. What is the use and usage of applet? 6.1 Profile

Threads are similar to the process, is a code that completes a particular function, is a single order flow control in the program; however, the process is different, and multiple threads of the same type are shared a memory space and a set of system resources, and thread itself Data typically only only the microprocessor register data, and a stack used in the execution of the program. Therefore, the system is generating a thread or when switching between each thread, the burden is much smaller than the process. For this reason, the thread is called light-weight process. A plurality of threads can be included in a process. A thread is a sequential control flow within a program. 1. Process: Each process has independent code and data space (process context), and the overhead of the process switching. 2. Thread: Lightweight Process, the same type thread sharing code and data space, each thread has a separate runtime stack and program counter (PC), and the overhead of thread switches. 3. Multi-process: In the operating system, you can run multiple task programs at the same time. 4. Multithread: In the same application, there are multiple sequential flows simultaneously.

6.1.1 Conceptual Model of Thread

Java is inherently supporting multi-threaded, all classes are defined under multithreading, and Java uses multithreading to make the entire system as an asynchronous system. The thread in Java consists of three parts, as shown in Figure 6.1. 1. Virtual CPU, package in the java.lang.Thread class. 2. The code executed by the CPU is passed to the THREAD class. 3. The data processed by the CPU is passed to the THREAD class.

6. 1. 2 threads (1)

Java's thread is implemented through the Java.lang.Thread class. When we generate a Thread class object, a new thread is generated.

This thread example represents the true thread in the Java interpreter, which can start thread, termination thread, thread hang, etc., each thread is defined in Java's software package java.lang through class Thread, its constructing method To: Public Thread (ThreadGroup Group, Runnable Target, String Name); where group indicates the thread group to which the thread belongs; Target actually performs the target object of the thread, it must implement the interface runnable; Name is the thread name. Each thread in Java has its own name, Java provides a different Thread class constructor, allowing the thread to specify the name. If Name is NULL, Java automatically provides a unique name. When a parameter of the above-described construction method is NULL, we can get the following constructor: public thread (); public thread (runnable target, string name); public thread (String name) Public Thread (ThreadGroup Group, Runnable Target); Public Thread (ThreadGroup Group, String Name); a class declaration implementation runnnable interface to act as a thread body, only one method is defined in the interface runnable (): public void Run ); Any object that implements the interface runnable can be used as a thread target object, and the THREAD itself also implements the interface Runnable, so we can implement line-enforcement through two ways. (1) Define a thread class, which inherits the threaded Thread and rewritten the method Run (), at which time the target target can be null when initializing the instance of this class, indicating that the thread body is executed by this instance. Since Java only supports single inheritance, the classes defined by this method cannot inherit other parent classes. (2) Provide a class of interface runnable as a thread target object. When initializing a thread class or thread subclass, pass the target object to this thread instance, the thread body Run () is supplied by the target object. . At this time, the class that implements the interface runnable can still inherit other parent classes. Each thread is a method RUN () through a particular THREAD object, and the method Run () is called a thread body. Figure 6.2 shows the different states of the Java thread and the modes call between the states. Figure 6.2 Status of thread

1. Create a state (New Thread) When performing the following statements: thread mythread = new mythreadclass (); When a thread is created, it is just an empty thread object, the system does not assign resources for it. . 2. Runnable "thread mythread = new mythread (); mythread.start (); When a thread is running, the system assigns the system resources to this thread, arrange it to run and call thread operation. Method, this is such that the thread is in a runnable state. It is important to note that this state is not running in the run, because the thread may actually run it actually. Since many computers are single-parallel, it is impossible to run all running threads at the same time, and Java's running system must be scheduled to ensure that these threads share the processor. 3. NOT RUNNABLE) There are several reasons for entering the uncomfortable state: 1) Call the SLEEP () method; 2) Call the SUSPEND () method; 3) is waiting for a conditional variable, thread calling Wait ) Method; 4) The input and output streams occur in the output stream; the uncomfortable state is also referred to as blocking state (Blocked). For some reason (input / output, waiting message, or other blocking case), the system cannot perform a state of threads. At this time, even if the processor is idle, the thread cannot be performed. 4. The termination of the Dead State (DEAD) thread can generally be implemented in two ways: natural undo (thread execution) or stopped (call the stop () method). It is not recommended to terminate the execution of the thread by calling STOP (), but let the thread execute 6. 1. 2 thread body (2)

Comparison of two methods of constructing liner: 1. Using Runnable interface 1) You can separate the CPU, code, and data, form a clear model; 2) can also inherit from other classes; 3) maintain the consistency of the program style. 2. Direct inheritance THREAD class 1) Cannot inherit from other classes; 2) Write simple, you can directly manipulate threads without using thread.currentthread ().

Example 6.2 Construction of the PUBLIC CLASS Clock Extends Java.applet.Applet Implements Runnable {// Implementing the Interface THREAD CLOCKTHREAD; public void start () {// This method is a method of applet, not a thread method if (ClockThread == NULL) {ClockThread = New Thread (this, "clock"); / * The thread body is the clock object itself, the thread name is "clock" * / clockthread.Start (); // start thread}}

Public void run () {// run () method is the content of thread execution while (clockth! = null) {repaint (); // Refresh display screen try {clockthread.sleep (1000); // Sleep 1 second, That is, execute once every 1 second} (InterruptedException E) {}}} public void Paint (GRAPHICS G) {DATE NOW = New Date (); // Get Current Time Object G.DrawString (now.GetHours () ":" now.getminutes () ":" now.getSeconds (), 5, 10); // Display Current Time} PUBLIC VOID STOP () {// This method is the method of applet, not a thread method Clockthread.stop (); clockthread = null;}}

6.1.3 Scheduling of thread

Java provides a thread scheduler to monitor all threads that enters ready state in the program. The thread scheduler determines which threads should be scheduled according to the priority of the thread. The thread scheduler selects the high priority thread (enter the run state) by thread, and the thread schedule is a predecessor scheduling, that is, if during the current thread execution, a higher priority thread enters the operational state. Then this thread is immediately scheduled.

The predecessor scheduling is divided into: time film mode and exclusive way. Under the time of time, the current active thread is executed after the current time film, if there is a thread that is in the same priority, the system will give the execution to other priority threads, the current active thread transfer Waiting for the execution queue, waiting for the next time piece scheduling. Under exclusive mode, once the current active thread is performed, it will always be executed until it is performed or actively discard the CPU due to some reason, or a high priority thread is ready. In the following cases, the current thread will discard the CPU: 1. The thread calls the Yield () or SLEEP () method to discard it; 2. Due to the current thread, I / O access, external read and write, wait for user input, etc. Resulting in thread blocking; or is waiting for a condition variable, as well as the thread calling WAIT () method; 3. Pre-first system, participate in scheduling by high priority thread; time film mode, the current time film is used, Level threads participate in scheduling.

The priority of the thread's priority thread is represented by numbers, ranging from 1 to 10, THREAD.MIN_PRIORITY to Thread.max_Priority. The default priority of a thread is 5, namely thread.norm_priority. The following method can operate the priority: int getPriority (); // Get the priority void setPriority (Int newPriority) of the thread; // When the thread is created, you can change the thread priority by this method.

Note: Note When running a Java program in all systems, the time-slice policy scheduling thread is used, so a thread should actively discard the CPU when you are idle, so that other threads with priority and low priority are performed.

6.2 Multi-threaded mutual exclusion and synchronization

The thread mentioned earlier in the critical resource issues is independent, and asynchronously, that is State or behavior. But there are often some simultaneous running threads to share data, at which point the status and behavior of other threads, otherwise the correctness of the operation of the program cannot be guaranteed.

Example 6.4 Class Stack {INT IDX = 0; // The initial value of the stack pointer is 0 char [] data = new char [6]; // Stack has 6 characters

Public void push (char c) {// stack operation DATA [IDX] = C; // data into the stack ID = ; // Pointer to move a bit}

Public char pop () {// out of the stack operation idx - -; / / Pointer to move a Return Data [IDX]; // Data Out Stack}} Two threads A and B are simultaneously using STACK's same instance Objects, A is pushing a data in the stack, and B is to POP from the stack. If the incompleteness of threads A and B on the operation of the Stack object, the failure of the operation can result in the failure of the operation, the specific process is as follows: 1) Data = | P | Q | | | | | | | | | | | | | | | | | | | | | | | |

2) A Execute the first statement in the PUSH, push R into the stack; DATA = | P | q | r | | | | | iDX = 2 3) A has not yet executed IDX statement, A execution is interrupted by B, B Execute a POP method, return Q: DATA = | P | q | r | | | | idx = 1 4] a Continue to perform the second statement of PUSH: DATA = | P | q | r | |, | | iDX = 2 The final result is equivalent to R without a stack. The reason for producing this problem is the incompleteness of the operation of shared data access.

6.2.1 mutual exclusion lock

In order to resolve the incompleteness of the operation, in the Java language, the concept of object mutual blaming is introduced to ensure the integrity of shared data operations. Each object corresponds to a tag that can be called "mutex", which is used to ensure that there is only one thread to access the object. Keyword synchronized contacts with the mutex lock. When an object is modified with synchronized, it is shown that the object can only be accessed by one thread at any time.

Public void push (this) {Synchronized (this) {// this represents the current object of Stack Data [idx] = C; IDX ;}} public char pop () {synchronized (this) {// this represents the current Stack current Object IDX -; RETURN DATA [IDX];}} SYNCHRONIZED In addition to the implementation of the object on the object, it can be placed in the method statement, indicating that the entire method is a synchronization method. Public Synchronized Void Push (CHAR C) {...} If Synchronized is used in class declarations, all methods in this class are synchronized.

6.2.2 Synchronization of Multithreading

This section will discuss how to control the operational progress between threads of mutual interaction, the synchronization problem between multi-threads, the following we will use multithreaded synchronization models: producers-consumer issues to explain how to achieve multi-thread synchronization. We refer to the thread used in the system as consumers, generate or release threads of similar resources, called producers. In the Java application below, the producer thread writes data in the file, and the consumer reads data from the file so that the two threads run in this program share the same file resource. Through this example, let's know how to synchronize them.

Example 6.5 Class SyncStack {// Synchronous Stack Class Private INDEX = 0; // Stack pointer initial value is 0 private char [] buffer = new char [6]; // Stack has 6 characters of space public synchronized void Push (char c) {// plus mutex while (index = = buffer.length) {// stack is full, can not stack try {this.wait (); // Waiting until there is a data} Catch (InterruptedException E) {}}

THIS.NOTIFY (); // Notify other threads put the data out stack buffer [index] = C; // data into the stack index ; / / pointer upward move}

Public synchronized char pop () {// plus mutex while (index == 0) {// stack no data, can not set up try {this.wait (); // Waiting for other threads into the stack, put The thread of the POP method is placed in the lock waiting / / queue until it is activated by the notify () method, ready state} Catch (InterruptedException E) {}}}

THIS.NOTIFY (); // Notify Other Threads Inn, activate the thread in the middle of the lock waiting queue to move the index- -; / / Pointer down move Return buffer [index]; // data outlet}}

Class Producer Implements Runnable {// Producer SyncStack TheStack; // Producer Class The generated letter is saved in the Sync Stack Public Product (SyncStack S) {THHESTACK = S;}

Public void Run () {char C; for (int i = 0; i <20; maath.random () * 26 'a'); // Randomly generate 20 characters of THESTACK .push (c); // put the character in the stack system.out.println ("Product:" C); // Print Character Try {Thread.Sleep ((int) (math.random () * 1000); / * Sleep every word thread is generated, * /} catch (interruptedException e) {}}}}

Class Consumer Implements Runnable {// Consumer Class SyncStack TheStack; // Consumer class gets the character from the synchronous stack public consumer (SyncStack s) {these Ack = S;} public void Run () {char C; for (int I = 0; i <20; i ) {c = there /pop (); // Read characters from the stack System.out.println ("consumed:" c); // Print character try {thread.sleep (INT) (Math.random () * 1000); / * Sleep every time you read a character thread * /} catch (interruptedException e) {}}}}

Public class synctest {public static void main (string args []) {syncstack stack = new syncstack (); // The following consumer class object and producer object is operated by the same synchronization stack object Runnable Source = New Producter (stack); runnable sink = new construction; thread t1 = new thread (source); // thread instantiation thread t2 = new three (sink); // thread instantiation T1.Start (); // thread Start T2.Start (); // Thread Start}} class product is a producer model, where the run () method defines the operation of the producer thread, cycle calling the push () method, 20 letters produced In the stack, after each time you execute the PUSH operation, call the SLEEP () method sleep a random time to give the opportunity to perform other threads. Class consUMer is a consumer model, a loop call () method, removes a data from the stack, take a total of 20 times, after each execution of the POP operation, call the SLEEP () method sleep a random time to give other threads opportunity.

In the above example, by using Wait () and Notify () methods to achieve the synchronization of the thread, the notifyAll () method is also used in synchronization. In general, there are two queues in each shared object. One is the lock waiting queue and the other is the lock application queue. The first thread in the lock application queue can operate the shared object, while the thread in the lock waiting queue will move into the lock application queue in some cases. The following is more than Wait (), notify () and notifyall () methods: (1) Wait, NOFITY, NotifyAll must be executed in the case where there is already a lock, so they can only appear within the range of the synchronized role, that is, the appearance In methods or classes modified with synchronized. (2) WAIT effect: Release the held lock, enter the waiting queue. (3) Notify: Wake the first thread in the WAIT queue and move it into the lock application queue. (4) NotifyAll's role: Wake up All threads in the WAIT queue and move them into lock application queues. Note: 1) Suspend () and resume () no longer use suspend () and resume () in JDK1.2, and its corresponding function is Wait () and Notify () is implemented. 2) STOP () no longer uses STOP () in JDK1.2, but through the flag to make the program normal execution. Example 6.6 is a typical example.

Example 6.6 Public Class Xyz Implements Runnable {Private Boolean TimeToquit = false; // Sign bit The initial value is a fake public void run () {while (! TIMETOQUIT) {// As long as the logo is fake, the thread continues to run ...}}}}

public void stopRunning () {timeToQuit = true;} // flag set to true, the program ends normally represents} public class ControlThread {private Runnable r = new Xyz (); private Thread t = new Thread (r); public void startThread () {T.Start ();} public void stopthread () {r.Stoprunning ();} // Terminate the thread operation by calling the stoprunning method}

6.3 java applet

6.3.1 Applet Introduction

Applet is a piece of code written in Java language, which can be run in your browser environment. It is mainly different from Application to its implementation. Application is from which the main () method starts running, and the applet is running in the browser. You must create an HTML file, telling the browser to load what Applet and how to run.

1. Applet example

Example 6.7 HelloWorld.java Source Program: Import Java.awt.graphics; // Introduction Graphics Import Java.Applet.Applet; // Introduction Applet class

Public class helloworld extends applet {string hw_text; public void init () {// init () method is the method of applet to execute hw_text = "Hello World";} public void Paint (Graphics G) {g.drawstring (hw_text, 25 , 25); // Display string hw_text in places where coordinates are (25, 25)

}

After the Applet program is written, you must first compile into a bytecode file with the Java compiler, then write the corresponding HTML file to properly execute, such as the HTML file HelloWorld.html written for running the above Applet program, as follows:

2. Applet security

"Sandbox" mechanism: Java Virtual Machine provides the applet to a well-running sandbox, once they try to leave the sandbox, will be prohibited. Since the applet is passed through the network, this inevitably makes people think of security issues. For example, some people write a malicious program read the user password through the applet and spread to the network, which will be a very terrible thing. Therefore, you must limit the small application. The browser disabled APPLET does the following: (1) Calling other programs at runtime. (2) File read and write operation. (3) Load dynamic connection library and call any local approach. (4) Try to open a socket for network communication, but the connected host is not a host that provides an applet.

◇ Applet class level:

◇ Applet's lifecycle small application's life cycle is more complicated relative to Application. Four methods involved in its life cycle (also inherited by the JAPPLET class): init (), start (), stop (), and destroy (). Next, you will first use the figure to represent a small application lifecycle, and then briefly describe these four methods.

There are four states in the life cycle of the applet: initial state, running state, stop state and dieting state. When the program executes the init () method, the Applet program enters the initial state; then immediately execute the start () method, the Applet program enters the run state; when the browser icon in which the Applet program is located or transferred to other pages, The Applet program is immediately executed, and the applet program enters the stop state; in the stop state, if the browser reloads the page on the Applet program, or the browser restores from the icon, the applet program is called soth (). Method, enter the run state; of course, when the browser is closed, the Applet program calls the destroy () method to enter the desime. ◇ Applet main method: 1. When INIT () creates an applet, the method is executed when the microfer is loaded when the appler is loaded with Java. In the life cycle of a small application, only the method is executed once, so some of the initialization operations can be performed in it, such as handling the parameters passed by the browser, add user interface components, loading images, and sound files. The small application has a default constructor, but it is accustomed to performing all initialization in the init () method, not within the default constructor.

2. Start () Multiple executions, when the browser is restored from the icon to the window, or is executed when the home page is returned. The system will automatically call the START () method after calling the init () method. And whenever the browser returns from the icon to the window, or when the user leaves the home page containing the applet, the system will execute a START () method. START () method is called multiple times in the life cycle of the small application to start the implementation of the small application, which is different from the init () method. The method is the main body of a small application, in which some tasks that need to be repeated or reactivate a thread, such as starting animation or playing sound, etc. 3. STOP () Multiple executions, when the browser turns into icon, or when leaving the home page, the main function is to stop some work consumption system resources. In contrast to start (), the STOP () method is automatically called when the user leaves the page or the browser turns an icon. Therefore, the method is also called multiple times in the life cycle. This makes it possible to stop some of the operating system resources (such as interrupt a thread) when the user does not pay attention to the small application, so as not to affect the running speed of the system, and does not need to go to call the method. If you do not include animations, sounds, etc. in your applet, usually don't have to overload this method. 4. DESTROY () is used to release resources. When the browser is executed normally, Java automatically calls this method when STOP () is turned off. Destroy () method is used to recover any memory resources that are independent of the system. Of course, if this applet is still active, Java calls the Stop () method before calling Destroy (). The following example uses these methods in the small application lifecycle. Example 6.8 Import java.awt.graphics; import java.applet.applet; public class hwloop extends applet {audioclip sound; // Sound clip object public void init () {sound = getaudioclip ("Audio / Hello.au") ; // Get sound pieces} public void paint (graphics g) {g.drawstring ("Hello Audio", 25, 25); // Display string}

Public void start () {sound.loop (); // Sound piece start play} public void stop () {sound.stop (); // Sound snap stop}}

In this example, the applet will continue after execution. If the browser icon is or transferred to another page, the sound stops playback; if the browser returns to normal or from other pages, the program continues to play sound.

Since the applet program is to be embedded in an HTML file, it will be executed normally, and the HTML file tags related to the Applet program are described below.

[Archive = ArchiveList] // The name of the file that needs to be pre-downloaded in the same codebase code width = Pixels Height = Pixels // Applet initial display space [codebase = codebaseurl] // code Address [ALT = AlternateText] // If the browser does not support Applet, the displayed alternative text [name = AppletInstanceName] // is named the applet, used for communication between the same page Applet [align = alignment] // Alignment, such as Left, Right, Top, Baseline ... [vSpace = Pixels] [HSPACE = Pixels] // Reserved Edge Blank> [] [] ... // Parameter name and its value [AlternateHTML] Note: 1) Show the Java's browser will display the ordinary HTML document between to support Java The browser, ignore the ordinary HTML document therein. 2) AppletViewer only supports tag, and other tags will not be displayed.

1.3.2 Applet's AWT Drawing

The AWT of the APPLET program mainly involves three methods: Paint () method, update () method and repaint () method, update () method, and Paint () methods have a graphics class parameter. Graphics is the key to the drawing, which can support two drawings: one is a basic drawing, such as: drawing, rectangle, circle, etc. The other is to draw image, mainly used for animation production. To draw a drawing, first find an object of a Graphics class. The parameters transmitted by the update () method and the Paint () method are objects of the Graphics class, so it is primarily drawing them by overloading them, which is often used in the animation program. We can also get an object of a Graphics class with a GetGraphics () method, like the objects transmitted in the Paint () method, as the objects transmitted in the Paint () method are the objects of the Graphics class corresponding to the member. A variety of drawing methods can be used for the object of the Graphics class. The graphical drawing method provided in Graphics is: Paint () // Details of the drawing, you must have programmers to rewrite update () // Update graphics, first clear the background, prospect, and then call Paint () repaint () / * Used to redraw the graphics, when the shape profile changes, that is, the size change or position movement, the repaint () method is automatically called by the system, and the actually repaint () method is automatically called Update () method * /

The following method supports basic drawing and painting images: void drawLine () void drawArc () void drawPolygon () void drawRect () void drawRoundRect () void fill3DRect () void fillOval () java.awt.Graphics output character class: void drawBytes () Void Drawchars () Void DrawString () 6.3.3 Communication between Applets and Browsers

Many methods are provided in the Applet class to communicate with the browser. The following is a brief introduction to these methods: A web page can contain more than one applet. Multiple minimal applications in a web page can communicate directly through the method provided in the Java.applet package.

GetDocumentBase () // Returns the URL getCodeBase () // of the current web page Returns the URL GetImage (URL BASE, STRING TARGET) // returned to the URL of the URL GetAudioClip (URL BASE, STRING TARGET) / / Return the URL Sound Object (String Target) / / The value of the parameter named target in the HTML file is extracted in the URL.

Communication between the same page applet provides the following method to get the environment context object of the current Run page in the Java.applet.applet class. Public AppleTContext (); You can get information about the current application running environment via AppletContext object. AppletContext is an interface that defines some methods to get other mini applications of the current page, which in turn implements communication between the same page. (1) to give the target environment context AppletContext public AppletContext getAppletContext currently running page (); (2) to obtain the object named name Applet public abstract Applet getApplet (String name); (3) obtained in this page Applet objects for all public abstract Enumeration GetApplets ();

[本 讲 小]

This lecture introduces the Java thread and some basic knowledge and simple applications of Java Applet. Through the thread introduction, the difference between thread and process is clarified, and the basic principle of thread is described and the constructor of the line body, Understand the basic characteristics of the thread and the conversion relationship and calling method of threads, and clarify the use of threads, and then we further describe several scheduling strategies for threads, and prioritize in different schedule policies. And how to perform basic thread control, threads' key and difficulties in multithreaded mutual exclusion, first we must understand the concept and role of mutual reversing, how to use mutex locks to control and process multithreaded synchronization issues.

The second half of this lecture We introduce Java Applet explanation and some basic applications, such as the creation of applets, life cycle and Applets, and Applet's AWT drawing, and finally introduce communication between Applet and browser. Methods.

转载请注明原文地址:https://www.9cbs.com/read-117781.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.034, SQL: 9