Programming for multithreaded programming, Java I/O systems, and Java graphical interfaces

Source: Internet
Author: User
Tags thread class

Multithreaded Programming:

A running program is often called a process , and each task is called a thread , and a program that runs multiple threads within a program is called a multithreaded procedure.

The difference between threads and processes: ① Each process requires the operating system to allocate a separate memory space for it;

② While all threads in the same process work in the same memory space , these threads can share the same block of memory and system resources.

Creation of Threads:

1) Create a thread by inheriting the thread class:

① create a class that inherits the thread class;

② rewrite the Run () method in the thread subclass that was created, and write the code in the method that you want the thread to run;

③ create an instance of the thread subclass;

④ starts running the thread by calling the start () method on the instance.

2) Create a thread by implementing the Runnable interface:

① creates a class that implements the Runnable interface, which is used to represent the tasks that we need to do with threads;

② the code that you want to execute in the thread within the method specified by runnable.

③ create an instance of the Runnable class;

④ creates a thread object and passes the instance of Runnable as a constructor parameter;

⑤ begins the execution of the thread by invoking the start () method of the instance of the thread class.

Two ways of connection and difference:

Contact: The thread class implements the Runnable interface, which means that the thread class is also a subclass of the runnable interface;

Difference: the way to implement the Runnable interface has several significant advantages over the way it inherits the thread class

① using the Runnable interface can effectively separate the virtual CPU (thread Class) from the task that the thread wants to accomplish, which embodies the basic principles of object-oriented design.

② can avoid the limitations of Java single inheritance.

Priority of the thread:

The order in which threads are run is not determined by the order in which the threads are created, but by the priority.

In addition to using the sleep () method to suspend a thread for a period of time, you can also use the yield () method to stop a thread from running.

Thread synchronization:

When more than two threads need access to shared resources, we must make sure that only one thread can access the shared resources at the same point in time, and that the process of running this target is called synchronization.

1. Sync Block: Synchronized (the object that acquired the lock) {

Code that needs to be locked

}

1) When a thread is running this block, other threads cannot use the block's code;

2) When a thread obtains an "object lock", if other threads also want to acquire the object lock, they must wait until the object lock is freed.

2. Synchronization method: eg:synchronized void Printvalue () {

System.out.println ();

}

Thread life cycle:

Thread state transition diagram:

1. New status

When a thread object is established with the new keyword and the thread class or its subclasses, the thread object is in a new state. The newly-emerging thread has its own memory space, which is entered in the ready state by calling the Start method (runnable).

Note: You cannot call the start () method again on a thread that is already started, or a java.lang.IllegalThreadStateException exception will occur.

2. Ready state

A thread in the ready state already has a running condition, but has not yet been assigned to the CPU and is in the thread-ready queue (albeit in the form of a queue, in fact, it is called a running pool rather than a running queue.) Because CPU scheduling does not have to be scheduled in FIFO order, wait for the system to allocate CPU for it. The wait state is not an execution state, and when the system selects a thread object waiting to be executed, it enters the execution state from the waiting execution state, and the system picks the action called "CPU scheduling". Once the CPU is acquired, the thread goes into a running state and automatically calls its own Run method.

Tip: If you want the child thread to execute immediately after calling the start () method, you can use the Thread.Sleep () mode to make the main thread sleep a bunch and go to execute the child thread.

3. Operation Status

A running thread is the most complex and can become a blocking state, a ready state, and a dead state.

A thread in the ready state, if the CPU is dispatched, is changed from the ready state to the running state, and the task in the Run () method is executed. If the thread loses its CPU resources, it becomes ready again from the running state. Re-wait for the system to allocate resources. You can also call the yield () method on a thread that is running, and it will let go of the CPU resource and become ready again.

When the following occurs, the thread changes from the running state to the blocked state:

①, thread calls the sleep method to voluntarily discard the system resources consumed

②, the thread calls a blocking Io method that is blocked until the method returns

③, Thread tries to get a synchronization monitor, but changes the synchronization monitor is being held by another thread

④, thread is waiting for a notification (notify)

⑤, the program calls the thread's suspend method to suspend the thread. However, this method can easily lead to deadlocks, so the program should avoid using this method as much as possible.

When the thread's run () method finishes executing, or is forced to terminate, such as an exception, or call the Stop (), Desyory () method, and so on, it transitions from the running state to the dead state.

4. Blocking status

A running thread in some cases, such as a sleep method, or waiting for a resource such as an I/O device, will give up the CPU and temporarily stop its own operation and go into a blocking state.

The thread in the blocking state cannot enter the ready queue. Only when the cause of the blockage is eliminated, such as when the sleep time has elapsed, or the waiting I/O device is idle, the thread goes into a ready state, queues up in the ready queue, and continues to run when the system has been selected and started from where it was originally stopped. There are three ways to pause threads execution:

5. Death status

When the thread's run () method finishes executing, or is forced to terminate, it is considered dead. This thread object may be alive, but it is not a separate thread. Once a thread dies, it cannot be resurrected. If you call the start () method on a dead thread, the java.lang.IllegalThreadStateException exception is thrown.

It is recommended that you use the Run method to end a thread in a way that controls the loop condition.

wait: tells the current thread to discard the object lock and enter the wait state until another thread enters the same object lock and calls notify.

Notify: Wakes the first thread of a call to wait in the same object lock.

Notifyall: Wakes all threads that call wait in the same object lock, and the thread with the highest priority is first awakened and executed.

 

Add:

Thread Sleep--sleep

If we need to let the currently executing thread pause for a while and go into a blocking state, you can call the sleep method of the thread

Threading Concession--yield

The yield () method is somewhat similar to the sleep () method, which is also a static method provided by the thread class, which also allows the currently executing thread to pause, yielding the CPU resources to other threads. But unlike the sleep () method, it does not go into a blocking state, but goes into a ready state. The yield () method simply pauses the current thread, re-enters the ready thread pool, and lets the system's thread scheduler reschedule again, which is entirely possible: when a thread calls the yield () method, the thread scheduler then dispatches it back into the run state execution. In fact, when a thread calls the yield () method to pause, the priority is the same as the current thread, or a thread with a higher priority than the current thread is more likely to get the chance to execute, of course, only possible, because we cannot accurately interfere with the CPU scheduler.

The full life cycle of a thread:

Photo Description:

1, the implementation of the thread has two ways, one is to inherit the thread class, the second is to implement the Runnable interface, but anyway, when we new this object, the thread entered the initial state;

2, when the object calls the start () method, it enters the operational state;

3, after entering the operational state, when the object is selected by the operating system, the CPU time slice will enter the running state;

4, the situation after entering the state of operation is more complicated:

When the ①run () method or the main () method finishes, the thread enters the terminating state;

② when a thread calls its own sleep () method or another thread's join () method, it goes into a blocking state (which stops the current thread, but does not release the resources it occupies). When sleep () ends or join () ends, the thread enters the operational state and continues to wait for the OS to allocate time slices;

The ③ thread calls the yield () method, which means to discard the currently acquired CPU time slice and return to the operational state, at which point the OS is at the same competitive state as the other processes, and it is possible that the process will go into the running state.

④ when a thread has just entered the operational state (note that it is not yet running), discovers that the resource to be called is Synchroniza (synchronous), acquires no lock token, will immediately enter the lock pool state and wait for the lock tag (at this point the lock pool may already have other threads waiting to acquire the lock tag, when they are in the queue state , on a first-come-first-served basis, once the thread obtains the lock tag, it goes to the operational state, waiting for the OS to allocate CPU time slices;

⑤ when a thread calls the Wait () method, it enters the waiting queue (which frees all the resources that it occupies, unlike the blocking state), which cannot be automatically awakened after it enters this state, and must rely on other threads to invoke the Notify () or Notifyall () method to be awakened ( Since notify () only wakes up a thread, we are not sure which thread is specifically awakened, perhaps the thread we need to wake up is not able to wake up, so in practice it is generally used with the Notifyall () method, which wakes up some threads), and the thread is awakened and enters the lock pool. Wait for the lock token to be acquired.

Java I/O system:

1. The Java class Library provides a number of classes that can help us read data from different devices and save or output them to different devices. These similarities are placed in the java.io package and the Java.nio package, collectively referred to as the Java I/O system.

2. Flow : We can interpret the stream as a conduit for transmitting data.

The stream is the basis of Java I/O and is the most basic abstraction of the Java language for I/O, the reason: The two most basic characteristics of a stream: ① contains liquid. Liquid is data;

The ② has a direction. The direction is read or write, that is, the input and output of information for the device.

Classification of streams:

1) input stream and output stream--according to the direction of the flow

Input stream: Reads data from the data source into the program. can only read and not write. The input streams in the IO package inherit from the abstract class outputstream or reader.

Output stream: Writes data from the program to the data destination. Can only write can not read. The output streams in the IO package inherit from the abstract class InputStream or writer.

2) byte stream and character stream-- stream is divided by the smallest unit of processing data

BYTE stream: Data is transmitted in bytes for the smallest unit. BYTE streams in IO packets inherit from the abstract class InputStream or OutputStream.

Character stream: Data transfer with Char as the smallest unit. The byte stream in the IO packet is inherited from the abstract class reader or writer.

3) node flow and processing flow--by the function of the stream

Node flow: Also called low-level flow, is a stream that can read/write data directly from/to a specific data source.

Processing flow: Also known as the Advanced Stream, the processing stream cannot be connected directly to the device, but instead connects to the existing stream, providing a more powerful read/write function for the program through the processing of the data.

How to tell the advanced stream, low-level stream: If the class's constructor has an existing stream as an argument, it is an advanced stream.

3. The class in the I/O library has a pair of: 1) The symmetry of the input stream and the output stream;

2) The symmetry of the byte stream and the character stream.

I/O operation steps:

① establish flow;

② operation Flow;

③ closes the stream.

4. File class : Treat a File object as a string that represents the name and location of a document or directory.

Common methods in the file class:

The Boolean CanExecute () tests whether the application can execute the file represented by this abstract path name.

Boolean CanRead () tests whether the application can read the file represented by this abstract path name.

Boolean canWrite () tests whether the application can modify the file represented by this abstract path name.

The int compareTo (File pathname) compares the two abstract path names in alphabetical order.

Boolean CreateNewFile () creates a new, empty file only if and only if there is no file with the name specified by this abstract pathname.

The static file Createtempfile (string prefix, string suffix) creates an empty document in the default temporary file directory, using the given prefix and suffix to generate its name.

The static file Createtempfile (string prefix, string suffix, file directory) creates a new empty document in the specified directory, using the given prefix and suffix string to generate its name.

A Boolean delete () deletes the file or directory represented by this abstract pathname.

void Deleteonexit () requests that the file or directory represented by this abstract path name be deleted when the virtual machine terminates.

Boolean equals (Object obj) tests whether this abstract pathname is equal to a given object. Boolean exists () tests whether the file or directory represented by this abstract pathname exists.

String GetName () returns the name of the file or directory represented by this abstract path name.

Boolean Isabsolute () tests whether this abstract path name is an absolute pathname.

Boolean isdirectory () tests whether the file represented by this abstract pathname is a directory.

Boolean isfile () tests whether the file represented by this abstract path name is a standard file.

Boolean Ishidden () tests whether the file specified by this abstract path name is a hidden file.

Long LastModified () returns the last time the file was modified by this abstract path name.

Long Length () returns the length of the file represented by this abstract path name.

String[] List () returns an array of strings that specify the files and directories in the directory represented by this abstract path name.

Boolean mkdir () to create the directory.

5. Byte stream: used to process binary files

Common methods in the Java.io.InputStream class:

int available () returns the number of bytes that can be read from the input stream

void Close () to close the input stream

int read (byte[] b) reads some bytes from the input stream, and buffers the bytes into buffer array B, and reads it back 1

int read (byte[] b, int off, int len) reads the first Len bytes of the data from the input stream development position off, and reads it into the byte-type data, and returns 1.

5. Character stream: for working with text files

Reader:bufferedreader

CharArrayReader

FilterReader

InputStreamReader

Pipedreader

StringReader

Writer:bufferedwriter

Chararraywriter

Filterwriter

Inputstreamwriter

PipedWriter

StringWriter

PrintWriter

5. Character stream: Object-based read-write, provided by Objectinputstream/objectoutputstream

Read-write object: ① corresponding class must implement Java.io.Serializable interface;

After the ② class is serialized, the object is read and written by Objectinputstream/objectoutputstream.

This property cannot be instantiated when the definition class is decorated with transient properties. This helps protect data security.

The process of using the ObjectInputStream class to split an object into a sequence of bytes after implementing an interface is called serialization, and the process of using the ObjectOutputStream class to restore a sequence of bytes to an object is called deserialization.

Java Graphical interface Programming:

Two sets of components are available in the 1.Java API to support the writing of graphical user interfaces, including AWT and Swing.

AWT: defined in your java.awt package

①AWT relies heavily on the underlying operating system-the appearance depends on the platform on which the program runs;

② low efficiency, AWT components are also known as heavyweight components;

③ development speed is faster.

Swing:

① lightweight GUI components;

② has better platform independence and portability;

2. Containers and Components : The Swing View section consists of two basic elements:

① components: Standalone visual controls, such as buttons, text fields;

② Container: A special type of component designed to place other components.

A component must be placed inside a container to be displayed. Therefore, all swing GUI components must have at least one component. Component three elements: content, appearance display, behavior.

Add (): Adds the component to the container;

RemoveAll (): Remove all components from the container;

Remove (Component c): Removes the specified component from the container;

Layout of the component in the container:

1) FlowLayout Manager (jpanel default): Streaming layout manager, component layout in left-to-right streaming order

Three constructors: public FlowLayout ()

public flowlayout (int align) align is the way it is: Flowlayout.center, Flowlayout.right, left

Oublic flowlayout (int align, int hgap, int vgap) Hgap: Horizontal spacing, vgap: Vertical spacing

2) BorderLayout Manager (jframe default): Border layout manager, divides the container into five regions in the first and the other. Only one component can be added per zone, and the component size is determined by the region

Two constructors: public Borderayout ()

Oublic borderayout (int hgap, int vgap) Hgap: Horizontal spacing, vgap: Vertical spacing

3) GridLayout Manager: Grid layout manager, grid of containers into rows and columns

Three constructors: public GridLayout ()

public GridLayout (int rows, int cols)

Oublic GridLayout (int rows, int cols, int hgap, int vgap) rows: Number of rows, cols: Number of columns

4) BoxLayout Manager: Box layout manager, components displayed in vertical or horizontal mode

A constructor: PublicGridLayout (Container target, int axis) creates a new BoxLayout manager for the specified target and given axis

Axis:BoxLayout.X_AXIS: Horizontally placed from left to right along the X axis;

Boxlayout.y_axis: Placed from top to bottom along the Y-axis direction.

3. Event-driven programming:

1) Event and event source

① event: Used to describe what happened;

Event Source: The component that generates an event and triggers it is called the event source.

② if a component can trigger an event, then any subclass of that component can trigger the same type of time.

2) Time Listener, registration, and handling events

Become an Event listener:

① Create a Listener object, the listener must be an instance of the corresponding event listener interface;

② registers the listener with the event source, and the registration method depends on the event type. Usually for xxx Event, the corresponding registration method is Addxxxlistener.

3) Define an optional method for the Listener class:

① the GUI program itself to implement the listener interface;

② uses the member inner class to define the listener class;

③ uses an anonymous inner class to define the listener class.

      

Programming for multithreaded programming, Java I/O systems, and Java graphical interfaces

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.