Java Getting Started tutorial (multi-threaded)

The concept of threads of
pure seed to after a task is completed then the mode of a task carried out, so start the next task must wait for the end of the previous task, and only after a task is completed before the next task. Java language provides concurrency mechanism that allows developers to execute multiple threads in the program, each thread to complete a function, and concurrently with other threads. This mechanism is called multi-threading. Operating system process as a unit, we are under Windows

The system may be assigned to the limited time period of each process executed by the CPU (also referred to as CPU time slice), the CPU performs a process this time, a period of time and then jump to the next process to execute another. Since the speed of the CPU switches quickly, giving the user the feeling that these tasks seem to run simultaneously, so the use of multi-threading technology, can run more different kinds of tasks at the same time.

Features single task is queued for execution, that is synchronous, after just enter a command in cmd, must wait until they have finished this command can be executed the next command.

CPU can switch back and forth between Tasks 1 and 2, that the task of having to wait five seconds before 2, run, be greatly enhance the efficiency of the system. This is to use multi-threading technology, the thread can be understood as a separate sub-tasks running in the process.

Implementation of
multi-threaded programming, there are two main ways: one is to inherit the Thread class, and the other is to achieve Runnable interface

Thread类
public Thread(String threadName)
public Thread()

the extends the Thread class newthread {public
@Override
public void run () {
// thread execution code
}
}
// Use
new NewThread () start (); .
service code needs to be set to achieve the thread run () method. When a class inherits from the Thread class, you can cover in this class run () method, write code that implements multithreading capabilities of the run () method, and then at the same time calling start Thread class () method thread of execution, that is, call run () method

Runnable interface
thread if you want to create a class has a parent, then you can not inherit the Thread class, because Java does not support multiple inheritance, it is necessary to implement Runnable to deal with such situations

public Thread(Runnable r);
public Thread(Runnable r,String name);

public class MyRunnable the implements the Runnable {
@Override
public void RUN () {
code execution thread //
}
}
// Use
the Runnable Runnable new new MyRunnable = ();
the Thread Thread new new = the Thread (Runnable);
Thread.start ();
thread lifecycle
thread also has a life cycle, including seven kinds of states, namely birth state, ready state, running state, the wait state, dormant state, blocking state and a state of death

Born Status: The status of the user is located when you create a thread, the thread until the user calls the instance start () method, threads are born in the state.

Ready state: also known as executable state, when the user calls start () method, the thread is in the ready state.

Operating status: When the thread to get the system resources into operation.

Wait state: when the thread is running under the call wait Thread class () method, the thread goes into a wait state. The thread will enter the wait state

Must call notify Thread class () method can be awakened. notifyAll () method is to wake up the thread at all in a wait state.

Sleep: When a thread calls Thread class sleep () method, it will go to sleep.

Blocked state: If a thread issues an input / output request in the operating state, the thread enters the blocked state, it waits for the input / output end, the thread into the ready state. On the blocked thread, even if the system resources are turned off, the thread still can not return to running.

Death Status: finished when threads run () method, the thread into the death state.

Synchronization mechanism synchronized
in order to share resources to deal with this competition, you can use the synchronization mechanism. The so-called synchronization mechanism, referring to the two threads simultaneously act on an object, the object should maintain the unity and integrity of the data. Java provides synchronized keyword, provides built-in support to prevent resource conflicts.

The synchronization method
class className {
public the synchronized type methodName () {
// Code
}
}
sync blocks
the synchronized (obj) {
// Code
}
public class Test {
Object obj = new new Object ();
public void Method () {
the synchronized (obj) {
// Code
}
}
}
multithreading and synchronous single thread of essentially different, when processing a very complex operations, using multi-threaded processing, only the synchronized code block will be executed sequentially for other traffic each code is executed in a different thread.

curentThread ()
returns the thread information about the code segment being called which thread

static void main public (String [] args)
{
// call currentThread () method to output the name of the current thread
System.out.println (Thread.currentThread () getName ().);
}
public class the MyThread the extends the Thread {
@Override
public void RUN () {
System.out.println (Thread.currentThread () getName ().);
}
}
the myThread myThread the myThread new new = ();
the Thread new new T = the Thread (myThread);
t.setName ( "myThread");
T .start (); // output myThread;
isAlive ()
action isAlive () method is to determine whether the current thread is active. What is it active? Is active thread has been started and has not been terminated. Thread the state is running or ready to run, I think the thread is the "Survival"

the MyThread the extends the Thread class public
{
@Override
public void RUN ()
{
System.out.println ( "RUN =" + this.isAlive ());
}
}
public static void main (String [] args)
{
the MyThread = new new MyThread the MyThread ();
System.out.println ( "the begin =" + mythread.isAlive ()); // output thread state
mythread.start (); // start threads
System.out.println ( "end =" + mythread.isAlive ()); // output thread state
}
// output
beginfalse
end
true or false // Here we must note that due to other start a thread to execute the code, end it is possible to perform (in this case end to false) before the thread is started, it is also possible to perform (in this case end is ture) after the thread starts
run to true =
sleep ()
the role of sleep () method is to let the current "executing thread" sleep within a specified number of milliseconds (suspended)

the MyThread the extends the Thread class public
{
@Override
public void RUN ()
{
System.out.println ( "Start");
the Thread.sleep (2000); delay of 2 seconds //
System.out.println ( "End");
}
}
getId ()
getId () made a running thread unique identification

The Thread = Thread.currentThread the Thread ();
System.out.println (thread.getId ());
thread pause
pause thread means that this thread can resume operation. Using suspend () method to suspend the thread, use resume () method resume the thread of execution

public class MyThread extends Thread
{
private long i=0;
public long getI()
{
return i;
}
public void setI(long i)
{
this.i=i;
}
@Override
public void run()
{
while(true)
{
i++;
}
}
}
public static void main(String[] args){
MyThread thread=new MyThread();
thread.start();
System.out.println(“线程开始”);
System.out.println(System.currentTimeMillis()+" i= “+thread.getI());//输出i的值
thread.suspend();//暂停
System.out.println(“线程暂停5秒”);
Thread.sleep(5000);
thread.resume();//开始
System.out.println (System.currentTimeMillis () + "i =" + thread.getI ()); // the value of i remain suspended
}
Note: When using the suspend () method to resume () method, if used improper synchronization objects can easily cause public is exclusive, so that other threads can not access a common synchronization object. Should pay particular attention when in use.

Thread stop
to stop a thread means that the operation processed before the thread stopped doing the task, which is to abandon the current operation. There are three ways to stop the thread

Use exit identification, the thread exits normally, that is, when the run () method to complete the thread to terminate.
Using the stop () method forcibly terminate the thread, but this method is not recommended, because the stop () and suspend () and resume (), the methods are invalid expired, their use may produce unpredictable results.
Use interrupt () method interrupt thread.
interrupt ()
action interrupt () method is used to stop the thread, but intermpt () using the effect of the method is not as loop structure break statement above, the cycle can be stopped immediately. Call intermpt () method is only a stop playing tag in the current thread, the thread is not really stop

public class MyThread extends Thread
{
@Override
public void run()
{
for (int i=0;i<10000;i++)
{
System.out.println(i+1);
}
}
}

static void main public (String [] args) {
the MyThread the MyThread new new thread = (); // Create a thread class instance MyThread13
thread.start (); // start threads
Thread.sleep (100); // delay of 100 ms
thread .interrupt (); // stop the thread
}
run results are shown below the main thread. As can be seen, although the call intermpt after a delay of 100 milliseconds () method to stop the thread thread, but that thread is still execute complete output 10000 rows of information.

Judge thread is not stopped
this.interrupted (): Tests whether the current thread has been interrupted.
this.islnterrupted (): Tests whether this thread has been interrupted.
stop ()
call to stop () method can be forced to stop a thread in any case

the MyThread the extends the Thread class {public
Private int I = 0;
@Override
public void RUN () {
the while (to true) {
I ++;
System.out.println ( "I =" + I);
the Thread.sleep (1000);
}
}
}
the MyThread the MyThread new new thread = ();
Thread.start ();
the Thread.sleep (8000);
Thread.stop ();
thread has a delay of 8000 milliseconds after the start, during this period will cycle 9, after the stop () method is executed so that the thread to stop. After running output 1-9

Java.lang.ThreadDeath will throw an exception when you call the stop () method, but under normal circumstances, this exception does not need to explicitly capture. Use stop () to release the lock will cause the results to data inconsistency. If this happens, the data processing program, there may be damaged, leading to erroneous program execution process, we must pay special attention.

Shenzhen construction site https://www.sz886.com

Guess you like

Origin blog.csdn.net/chenmh12/article/details/91411370