Off-thread

xiaoxiao2021-03-05  24

Thread: (good things)

Why use threads:

1. Improve the throughput or efficiency of the system. (I / 0 waiting)

2. Provide a sensitive user operation.

Example:

Part 1 principle

definition:

The instruction sequence executed in the internal order. The thread itself does not own resources (there is no resource), such as memory space. But it can use the resources of the process.

The difference between thread and processes:

1. From the perspective of resource allocation

The process is the basic unit of resource allocation, and threads themselves have no resources.

2, from the perspective of program scheduling

The process can contain multiple threads, which is the basic unit of program scheduling.

3, from the system's overhead angle

The system overhead of the process of creating the process is overhead for the time overhead of the thread creation process, because the process creates a resource for him, and the system's system for this process is large, and the resources of the thread share process are not required.

4, from concurrency angle

The process and threads can be made concurrently during the execution, but the particle size of concurrency is different. The process is concurrent as the application level, such as: such as song song and writing program. And threaded and published the functionality of the application inside, such as: Images and sound in the movie.

for example:

1, process and thread

2, very good cases of threads must be clear

The status of the process:

The necessary conditions for the process run:

1, own resources

2, have a CPU time

Three states:

Running: When the state running on the process is running (with resources and CPU)

Ready: When the thread has resources but no CPU time, the state of the CPU time is.

Blocking Status: When the thread is waiting for the state of the resource.

Pent state:

New: The state that has just been created has not been submitted.

Termination: End run.

The thread in the second part Java.

Creation of thread:

Two creation methods:

1, inherit the THREAD class.

Declare a subclass of a Thread class and override the Run () method.

Class mythread extends thread {

Public void run () {/ * overwrites this method * /}

}

2. Implement the runnable interface.

Declare a class that implements the runnable interface and implements the Run () method.

Class Mythread Implements Runnable {

Public void Run () {/ * implementation this method * /}

}

EX1:

Public class createwinthread extends thread {

Private Int countdown = 5;

Private static int threadcount = 0;

Public SimpleThread () {

Super (" threadcount); // Store the thread name

START ();

}

Public string toString () {

Return "#" getName () ":" countdown;

}

Public void run () {

While (true) {

System.out.println (this);

IF (- countdown == 0) Return;

}

}

Public static void main (String [] args) {

For (int i = 0; i <5; i )

New CREATEWINTHREAD ();

}

}

The main method of thread:

Run (): Write the function to be completed in this method. Start (): Reduces the thread from a new architecture to a ready state.

The actual execution of threads will be responsible for JVM and OS.

l The time to perform is unable to determine (multithreaded)

l The order of execution is unable to determine (multithreaded)

l The result of the execution is unable to determine (multithreaded)

Several constructor inheriting THREAD:

l thread (), create a Thread object with default name

l Thread (String Name), create a Thread object with the name of the specified Name parameter

l Thread (Runnable Target) creates a Thread object with a class that implements the Runnable interface.

l Thread (Runnable Target, String Name) Creates a THREAD object with a class that implements the Runnable interface, the thread is the name specified by the Name parameter.

EX2:

Public Class CreatewithRunnable Implements Runnable {

Private Int countdown = 100;

Public string toString () {

Return "#" thread.currentthread (). getname ()

":" countdown;

}

Public void run () {

While (true) {

System.out.println (this);

IF (- countdown == 0) Return;

}

}

Public static void main (String [] args) {

For (INT i = 1; i <= 5; i )

New Thread (New CreatewithRunnable (), " i) .Start ();

}

}

CurrentThread (): Get the current thread

GetName (): Get the name of the thread

There is only one Run method in the runnable interface. No start () cannot turn the thread from the new state to the read state, so the thread cannot be run. Runnable must be converted to the Thread class. Can run.

Create a reactive user interface

Public class friendlyui {

Private static int i = 0;

Public static void main (String [] args) {

New stoprun (). start ();

Compute compute = new computer ();

Compute.seti (i);

Compute.start ();

}

}

Class Stoprun Extends Thread {

PRIVATE STRING FLAG = ""

Public void setflag () {

Try {

InputStreamReader Reader = New InputStreamReader (System.in);

BufferedReader Input = New BufferedReader (Reader);

System.out.println ("If you want to terminate the program, please enter an exit");

THIS.FLAG = INPUT.READLINE ();

} catch (ioexception e) {

E.PrintStackTrace ();

}

}

Public void run () {

While (! Flag.equals ("exit")) {this.setflag ();

}

System.exit (0);

}

}

Class compute extends thread {

Private INT i = 0;

Public void seti (int i) {

THIS.I = I;

}

Public int geti () {

Return I;

}

Public void run () {

While (true) {

i ;

}

}

}

Sleep (): Let it stop in a millisecond time

Yielding (): Transfer the control of threads over other threads

Join (): After the thread process is completed, the control is transferred.

Guarding thread (wizard thread, monitoring thread, service thread)

The so-called "daemon thread" means that as long as the program is still running, it should provide a thread for a public service in the background, but the guardian thread does not belong to the core part of the program. Therefore, when all the non-standard threads are running, the program is over. Instead, as long as there is a non-guarded thread running, the program cannot end. For example, the thread running main () belongs to the non-daemon thread.

EX3 (Sleep, Yield, Join)

Public class yieldingthread extends thread {

Private static test monitor = new test ();

Private Int countdown = 100;

Private static int threadcount = 0;

Public yieldingthread () {

Super ("" threadcount);

START ();

}

Public string toString () {

Return "#" getName () ":" countdown;

}

Public void run () {

While (true) {

System.out.println (this);

IF (- countdown == 0) Return;

// yield ();

Try {

Sleep (1000);

} catch (interruptedexception e) {

E.PrintStackTrace ();

}

}

}

Public static void main (String [] args) {

For (int i = 0; i <5; i )

Try {

New yieldingthread (). Join ();

} catch (interruptedexception e) {

// TODO automatically generates a Catch block

E.PrintStackTrace ();

}

// new yieldingthread ();

}

}

Friendly user interface

Import java.io.bufferedreader;

Import java.io.ioException;

Import Java.io.InputStreamReader;

Public class friendlyui {

Private static int i = 0;

Public static void main (String [] args) {

New stoprun (). start ();

Compute compute = new computer ();

Compute.seti (i);

Compute.start ();

}

}

Class Stoprun Extends Thread {Private String Flag = ""

Public void setflag () {

Try {

InputStreamReader Reader = New InputStreamReader (System.in);

BufferedReader Input = New BufferedReader (Reader);

System.out.println ("If you want to terminate the program, please enter an exit");

THIS.FLAG = INPUT.READLINE ();

} catch (ioexception e) {

E.PrintStackTrace ();

}

}

Public void run () {

While (! Flag.equals ("exit")) {

THIS.SETFLAG ();

}

System.exit (0);

}

}

Class compute extends thread {

Private INT i = 0;

Public void seti (int i) {

THIS.I = I;

}

Public int geti () {

Return I;

}

Public void run () {

While (true) {

i ;

}

}

}

Priority between threads:

1-10

NORM_PRIORITY = 5

Min_priority = 1

Max_Priority = 10

Set by setPriority ()

Although JDK provides a 10-level priority, it is not well mapped to many operating systems. For example, there are seven levels on the Windows 2000 platform, so the mapping is uncertain (although the SUN Solaris has 231 levels). To maintain portability, the only way is to stare at Min_Priority, Norm_Priority, and Min_prority when adjusting priority.

Collaboration between threads

l thread mutual exclusion resources

l Thread synchronization

Thread mutual exclusion resources:

Critical area: A common memory space or device for two or more threads.

Various threads may have conflicts when using critical regions.

Public class createmutexthread extends thread {

Static varclass varclass = new varclass ();

/ *

The content in the RUN method is the content to be executed in the thread.

* /

Public void run () {

While (true) {

VARCLASS.SETI ();

INT number = 0;

Number = VARCLASS.GETI ();

IF ((Number% 2)! = 0) {

System.out.println (GetName () " VARClass.Geti ());

System.exit (0);

}

}

}

Public static void main (String [] args) {

For (int i = 0; i <10; i ) {

New createmutexthread (). START ();

}

}

}

Class varclass {

INT i = 0;

Public void seti () {

i ;

i ;

}

Public int geti () {

Return I;

}

}

Solution:

Set a statement to lock and unlocked before and after the code, only one thread can perform this code at the same time. Each object has a lock (also known as the Monitor Monitor), which is a thing of the object (so you don't have to write any code for this). This object is locked when you call the Synchronized method. No other Synchronized method for the same object before the method is returned and unlocked, no one other SYNCHRONIZED method. Just say the two methods, if you call F (), then before f () returns and unlock, you cannot call G () of the same object. So for any particular object, all Synchronized methods share a lock, and this lock can prevent two or more threads from reading and writing a shared memory at the same time.

Public class createmutexthread extends thread {

Static varclass varclass = new varclass ();

/ *

The content in the RUN method is the content to be executed in the thread.

* /

Public void run () {

While (true) {

VARCLASS.SETI ();

INT number = 0;

Number = VARCLASS.GETI ();

IF ((Number% 2)! = 0) {

System.out.println (GetName () " VARClass.Geti ());

System.exit (0);

}

}

}

Public static void main (String [] args) {

For (int i = 0; i <10; i ) {

New createmutexthread (). START ();

}

}

}

Class varclass {

INT i = 0;

Synchronized public void seti () {

i ;

i ;

}

Synchronized public int GETI () {

Return I;

}

}

Synchronize:

The result of a thread is used when another thread is running.

Class Order {

Private static int i = 0;

Private Int count = i ;

Public order () {

IF (count == 10) {

System.out.println ("Out of Food, Closing");

System.exit (0);

}

}

Public string toString () {Return "Order" count;

}

Class waitperson extends thread {

Private restaurant restaurant;

Public WAITPERSON (Restaurant R) {

Restaurant = R;

START ();

}

Public void run () {

While (true) {

While (Restaurant.Order == NULL)

Synchronized (this) {

Try {

Wait ();

} catch (interruptedexception e) {

Throw new runtimeException (e);

}

}

System.out.println (

"WAITPERSON GOT" Restaurant.Order);

Restaurant.Order = NULL;

}

}

}

Class Chef Extends Thread {

Private Restaurant Restaurant; Private WaitPerson WaitPerson;

Public Chef (RESTAURANT R, WAITPERSON W) {

Restaurant = R;

WAITPERSON = W;

START ();

}

Public void run () {

While (true) {

IF (Restaurant.Order == NULL) {

Restaurant.order = new order ();

System.out.print ("ORDER UP!");

Synchronized (waitperson) {

WAITPERSON.NOTIFY ();

}

}

Try {

Sleep (100);

} catch (interruptedexception e) {

Throw new runtimeException (e);

}

}

}

}

Public class restaurant {

ORDER Order; // package access

Public static void main (String [] args) {

Restaurant Restaurant = new restaurant ();

WAITPERSON WAITPERSON = New WaitPerson (Restaurant);

Chef CHEF = New Chef (Restaurant, Waitperson);

}

}

Synchronous example 2:

Public class testthread {

Static sharedate sharedate = new sharedate ();

Public static void main (String [] args) {

SetValue SetValue = New SetValue (Sharedate);

SetValue.start ();

New getValue (Sharedate, SetValue) .start ();

}

}

Class sharedate {

Private string [] strign = new string [10];

Private int index = 0;

Synchronized public string getStrvalue () {

Index -;

Return Strvalue [Index 1];

}

Synchronized public void setstrvalue (string value) {

INDEX ;

THIS.STRVALUE [INDEX-1] = Value;

}

Synchronized public int getIndex () {

Return Index;

}

}

Class getValue extends thread {

Private shadate shadate;

Private setValue setValue;

PRIVATE INDEX;

Public getValue (Sharedate Sharedate, SetValue SetValue) {

THIS.SHAREDATE = sharedate;

THIS.SETVALUE = setValue;

}

Public void run () {

While (true) {

INDEX = sharedate.getIndex ();

System.out.println ("GetValue" index);

IF (INDEX == 0) {

Synchronized (setValue) {

SetValue.notify ();

}

Try {

Sleep (100);

} catch (interruptedexception e) {

// TODO automatically generates a Catch block

E.PrintStackTrace ();

}

Yield ();

} Else if (INDEX> = 0 && index <= 9) {

System.out.println (Sharedate.getStrValue ());

}

}

}

}

Class setValue Extends thread {

Private shadate shadate;

Int index;

Public setValue (sharedate shadate) {

THIS.SHAREDATE = sharedate;

}

Public void run () {

INT i = 0;

While (true) {

this.index = sharedate.getIndex ();

System.out.println ("setValue" index);

IF (INDEX> = 9) {

Synchronized (this) {

Try {

THIS.WAIT ();

} catch (interruptedexception e) {

// TODO automatically generates a Catch block

E.PrintStackTrace ();

}

}

} else {

Sharedate.setstrvalue (" i);

i ;

}

}

}

}

Three parts: summary

1. Creation of threads (two creation methods)

2, thread properties and methods

3, the state of thread

Thread state

The state of the thread can be summarized as the following four:

New: Thread object has been created, but it has not been started (start), so it is not possible to run. Runnable: A thread in this state, as long as the timing mechanism is assigned to its CPU cycle, it can run. That is to say, specifically to some time, it may be running, or may not run, but when the turn is running, no one can stop it; it has no dead, nor is it blocked. DEAD: To abort the thread, the normal practice is to exit Run (). Before Java 2, you can also call STOP (), but it is not recommended to use this method because it is likely to cause instability of the program running. There is also a destroy () (but it has not been implemented, maybe it will not be in the future, that is, it has been given up). Behind we will use other ways to implement STOP () functionality. Blocked: In terms of thread itself, it can run, but there is anything else reason to block it from running. The thread scheduling mechanism will skip the blocks of the Blocked and do not assign the CPU time. I can't do anything unless it reaches the Runnable status.

Enter the blocking state

If the thread is blocked, it must be any problem. The problem may have the following:

You use the Sleep (MilliseConds) method to call the thread sleep. During this time, the thread cannot be run. You use the wait () method to hang the thread. Unless received the notify () or notifyAll () message, the thread cannot re-enter the RunNable status. This part of the content will be told later. The thread is at the end of the I / O. The thread wants to call another object's synchronized method, but has not yet obtained the lock.

Perhaps you have also seen suspend () and resume () in the old code, but Java 2 has given up these two methods (because it is easy to cause dead locks), so it will not be introduced here.

Post-class exercises:

l Understand the daemon L thread sharing usage resources

l thread mutual exclusion resources

l Thread synchronization

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

New Post(0)