Java Learning Journal (threads)

Source: Internet
Author: User
Tags constructor continue execution implement interface sleep thread thread class
First, the concept of the thread:
A thread is similar to a process and is a piece of code that completes a particular function. is a single sequence of flow control in a program, but unlike a process, multiple threads of the same type share a chunk of memory and a set of system resources, while the data for the thread itself usually has only the microprocessor's register data and a stack to use when the program executes. So the system is less burdensome than the process when it comes to creating a thread or switching between threads, which is why threads are called light load processes (Light-weight process). You can include multiple threads in a process.

A thread is a sequential flow of control within a program.
1. Process: Each process has a separate code and data space (process context), and process switching costs a lot.
2. Threads: Lightweight processes that share code and data space with the same class of threads, each with a separate run stack and program counter (PC), with little overhead for thread switching.
3. Multi-process: In the operating system, can run multiple task programs at the same time.
4. Multithreading: In the same application, there are multiple sequential streams executing concurrently.

Java internally supports multiple threads, all of which are defined in multithreading, and Java uses multithreading to make the entire system an asynchronous system.
1. Virtual CPU, encapsulated 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.

Second, the construction of the thread
A thread instance represents a real thread in the Java interpreter, through which it can start, terminate, and thread suspend, and each thread is defined in the Java package Java.lang through class thread, which is constructed by:

Public Thread (Threadgroup group,runnable target,string name);

Where group indicates the thread group that the thread belongs to, Target actually executes the target object of the thread body, it must implement interface runnable; name is the thread name. Each thread in Java has its own name, and Java provides a different thread class constructor that allows the thread to be given a name. If name is NULL, Java automatically provides a unique name.
When one of the parameters of the constructor above is null, we can get the following construction methods:

public Thread ();
Public Thread (Runnable target);
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 implements the Runnable interface to act as a thread body, and only one method run () is defined in the interface runnable:
public void run ();

Any object that implements the interface runnable can be the target object of a thread, and class thread itself implements the interface runnable, so we can implement the thread body in two ways.

(i) defines a thread class that inherits thread class thread and overrides the method run (), when an instance of this class is initialized, the target targets can be null, representing the thread body being executed by this instance pair. Because Java only supports single inheritance, classes defined in this way can no longer inherit other parent classes.

(ii) Providing a class that implements the interface runnable as the target object of a thread, passing the target object to the thread instance when initializing a thread object of the threads class or the threading subclass, which provides the thread body run (). At this point, the class that implements the interface runnable can still inherit other parent classes.



Third, the state of the thread
Each thread completes its operation through the method run () of a particular thread object, and method run () is called the thread body. The following illustration shows the different states of a Java thread and the methods invoked by transitions between states.

1. Create status (new Thread)
When you execute the following statement, the thread is in the created state:
Thread mythread = new Thread ();
When a thread is created, it is simply an empty thread object, and the system does not allocate resources to it.

2. Operational status (Runnable)
Thread mythread = new Thread ();
Mythread.start ();
When a thread is in a running state, the system allocates the system resources it needs to the thread, schedules it to run, and invokes the thread to run the method, which makes the thread operational (Runnable). Note that this state is not a running state (Running), because the thread may not actually be running. Since many computers are single-processor, it is not possible to run all of the running threads at the same time, and the Java operating system must implement scheduling to ensure that these threads share the processor.
  
3. Non-operational status (not Runnable)
There are several reasons for entering a non-functioning state:
1) called The Sleep () method;
2) called the Suspend () method;
3) for waiting for a condition variable, the thread calls the Wait () method;
4 thread blocking occurs in the input-output stream;
A non-running state is also known as a blocking state (Blocked). The system cannot execute the state of the thread for some reason (input/output, wait messages, or other blocking conditions). At this point, the thread cannot be executed even if the processor is idle.

4. State of Death (Dead)
The termination of a thread can generally be implemented in two ways: Natural undo (the thread finishes) or it is stopped (calls the Stop () method). It is not currently recommended to terminate the execution of a thread by calling stop (), but to have the thread run out.


Some of the long ways of threading
1. Sleep (long Millis)
This method is a static method, which means that we can call it directly, such as Thread.Sleep (5000), which means that the currently running line enters upgradeable stop and wait 5000 milliseconds. One thing to note: it is not certain that this thread will be executed immediately in 5000 milliseconds.

2.interrupt ()
This method is used to interrupt a thread (feeling that the process in sleep is more appropriate). The role of this method can be seen as an example:
public class Testinterrupt extends Thread
{

/** creates a new instance of Testinterrupt * *
Public Testinterrupt ()
{
}

public void Run ()
{
Try
{

for (int i=0; i<5; i++)
{
System.out.println ("Running" + i);
}
Thread.Sleep (10000);

for (int i=6; i<10; i++)
{
System.out.println ("Running the second loop" + i);
}

}catch (interruptedexception IE)
{
System.out.println ("Sleep Interrupted in Run ()");
for (int i=11; i<15; i++)
{
System.out.println ("Running the third loop" + i);
}

}

}

public static void Main (string[] args)
{
Testinterrupt ti = new Testinterrupt ();
Thread t = new Thread (TI);
T.start ();

Delay for a few seconds to let the other thread get going
Try
{
Thread.Sleep (2500);
}catch (interruptedexception IE)
{
System.out.println ("Sleep Interrupted in Main ()");
}

System.out.println ("About to wake up of the other thread");
T.interrupt ();
System.out.println ("Exiting from Main");

}
}

In the example above, if there is no t.interropt (), the program is running
for (int i=6; i<10; i++)
{
System.out.println ("Running the second loop" + i);
}
Plus what you do in the future is the content of the catch.

3.join () and join (long Millis)
Join () This function is to make the currently running thread if a stop for a, until the call join () method of this thread B is executed, and then continue a start thread A;
Look for an example:
public class TestJoin1 extends Thread
{

/** creates a new instance of TestJoin1 * *
Public TestJoin1 ()
{
}

public void Run ()
{
Try
{

for (int i=0; i<5; i++)
{
System.out.println ("Running" + i);
}
Thread.Sleep (1000);

for (int i=6; i<10; i++)
{
System.out.println ("Running the second loop" + i);
}

}catch (interruptedexception IE)
{
System.out.println ("Sleep Interrupted in Run ()");
}

}

public static void Main (string[] args)
{
Try
{
TestJoin1 ti = new TestJoin1 ();
Thread t = new Thread (TI);
T.start ();
T.join ();

for (int i=11; i<15; i++)
{
System.out.println ("Running the third loop" + i);
}
}catch (interruptedexception IE)
{
System.out.println ("Join Interrupted in Run ()");
}

System.out.println ("Exiting from Main");

}
}
The result of this program is that the thread (in fact, main) that T.join () is running at all times, has finished all the contents of the T thread, and then goes back to the T.join () that the main thread continues to do, and the rest of the statement. If the T.join () is removed, The result of running on a typical computer should be to do all the content in main and then do the contents of the T thread.

Join (long Millis) This method is almost the same as the join () method, where the executing thread A is shelved to do the contents of the run of thread B of the method called join (Long Millis). But later on Millis This parameter determines how much time b this thread can be run (Millis represents how many milliseconds), Millis after Hao second, the B thread will return to thread a even if it is not finished running.
The following procedure is a good illustration of this problem:
public class TestJoin2 extends Thread
{

/** creates a new instance of TestJoin2 * *
Public TestJoin2 ()
{
}

public void Run ()
{
Try
{

for (int i=0; i<5; i++)
{
System.out.println ("Running" + i);
}
Thread.Sleep (3500);

for (int i=6; i<10; i++)
{
System.out.println ("Running the second loop" + i);
}

}catch (interruptedexception IE)
{
System.out.println ("Sleep Interrupted in Run ()");
}

}

public static void Main (string[] args)
{
Try
{
TestJoin2 t2 = new TestJoin2 ();
Thread t = new thread (t2);
T.start ();
T.join (3000);

for (int i=11; i<15; i++)
{
System.out.println ("Running the third loop" + i);
}
}catch (interruptedexception IE)
{
System.out.println ("Join Interrupted in Run ()");
}
System.out.println ("Exiting from Main");

}
}

After watching so much, it seems like it's easy to create a misunderstanding join () This function is to let the calling method's thread B priority (first) be executed. In fact, this is not the case, the role of join () as mentioned above, it can only allow the current running thread a hold on, and so on, and so on after the execution of B.
The following procedure allows people to eliminate this misconception:
public class Test extends Thread
{
Public Test (String a)
{
Super (a);
}


public void Run ()
{
System.out.println (This.getname ());
}

public static void Main (String [] args)
{
Test a = new test ("a");
Test B = new Test ("B");
Test c = new test ("C");

A.start ();
B.start ();
C.start ();
Try
{
C.join ();
}
catch (Exception e) {
}
System.out.println ("This is main!");
}
}

See the run result is a,b first executed, then is C, finally is main ^^;

4. About synchronized
The purpose of this keyword is to allow several threads to synchronize, for example, in the simplest case. A cinema has 20 tickets to sell, and it has 3 conductors.
Write a program to verify that the result of not using synchronized is good, and you need to use the sleep () function to create this possibility (the timing of the thread's execution is unexpected):
public class Sell
{
public static void Main (String [] args)
{
Sellthread sell = new Sellthread ();
Thread sell1 = new Thread (Sell, "sellman1");
Thread sell2 = new Thread (Sell, "sellman2");
Thread sell3 = new Thread (Sell, "sellman3");
Sell1.start ();
Sell2.start ();
Sell3.start ();
}
}

Class Sellthread implements Runnable
{
private int i = 20;
public void Run ()
{
while (true)
{
if (i > 0)
{
Try
{
Thread.Sleep (100);
catch (Exception e)
{
}

System.out.println (Thread.CurrentThread (). GetName () + "sell" + i--);
}
}
}
}

The result was a total of 22 tickets sold (it is estimated that the cinema will be delighted to receive more tickets for no reason, but may soon face angry customers ...)
This time our synchronized should play the role of ^ ^ Modify the procedure as follows:
public class Sell2
{
public static void Main (String [] args)
{
Sellthread sell = new Sellthread ();
Thread sell1 = new Thread (Sell, "sellman1");
Thread sell2 = new Thread (Sell, "sellman2");
Thread sell3 = new Thread (Sell, "sellman3");
Sell1.start ();
Sell2.start ();
Sell3.start ();
}
}

Class Sellthread implements Runnable
{
private int i = 20;
String a = "Now ok!";
public void Run ()
{
while (true)
{
Synchronized (a)
{
if (i > 0)
{
Try
{
Thread.Sleep (100);
catch (Exception e)
{
}

System.out.println (Thread.CurrentThread (). GetName () + "sell" + i--);
}
}
}
}
}

That's it. Only 20 tickets will be sold. The parentheses in synchronized () are required for a class object so we can't write it directly in parentheses, we define a string object A,a flag (not knowing what to say is more appropriate) originally 1 for everyone to use, Such a conductor Selln to the ticket-selling thread to get a after he can start selling tickets, at the same time he put the object of a flag to 0, and then the other conductor ticket sales to find that they can not get the object of a is only the first set aside. The Selln ticket thread released the A,A flag and then became 1, This time the other conductor's ticket-selling thread will be able to compete, to see who gets the A object first. But string A has nothing to do with selling tickets, so we can use this to replace a in synchronized (), and it's the same as the effect of a that means who gets the this object to execute.


Here are two easily misunderstood places:
(1). After a thread gets the object in the synchronized bracket, Other threads that need to get this object to run cannot be executed. In fact, other threads can also be executed, but when they execute the object in need of synchronized, they found that the object's flag is 0, so can only be shelved again. (It seems that the goddess of fortune can only patronize one person ^ ^) so we use synchronized to make thread synchronization at the expense of efficiency, so do not need to use the place is not good.

(2) When a thread gets the object in the synchronized bracket, no other thread can execute it. In fact, if other objects that do not need to be synchronized can continue to execute, the thread may run along with the thread that gets the object in the synchronized bracket.

Some methods have been added to the front of the synchronized. In fact, this time is the caller of this method, that is, the flag flag of this 0, he cannot and other need this to run with the thread, but can be with other threads do not need this object to run together.

5.wait () and notify () or Notifyall ()
This several functions are designed to allow several synchronized threads to execute in a certain sequence.
are used with synchronized (), and the object in () is obj.
One thing to be aware of is that we should allow the Obj.wait line enters upgradeable to start. Because the order of execution is the thread A that requires obj.wait () to start first, and then it runs to Obj.wait (), it enters the shelve state and lets other threads execute first. The thread B with Obj.notify () is then executed, until B executes to obj.notify () (Obj.notify () is actually notifying the thread that the obj.wait () is On hold: "It's Your Turn"), and B is on hold, Then continue to do a obj.wait () later content.
So if we let the thread B with Obj.notify () run first, then B executes obj.notify () does not find any threads that enter the shelve state because of obj.wait (). Then start with a obj.wait () The thread a words. A runs to the obj.wait () and waits for the obj.notify () in another thread to wake it up, but unfortunately it will never be, because the thread with the Obj.notify () has been to the shelved thread to find it once, Unfortunately, it was not found. So thread A has been on hold ... (Feeling a bit like a love play ...);
For example, good:
public class ThreadTest
{
public static void Main (String [] args)
{
Storage stor = new Storage ();
Counter a = new Counter (stor);
Printer B = new Printer (stor);


A.start ();
B.start ();
}
}

Class Storage
{
public int i = 0;
}

Class Counter extends Thread
{
Private Storage A;
Public Counter (Storage stor)
{
A = Stor;
}

public void Run ()
{
System.out.println ("Hi");
Try
{
Sleep (100);
}
catch (Exception e) {}
int i = 0;
while (I < 5)
{
Synchronized (a)
{
System.out.println ("Counter");
A.I = (int) (Math.random () *50);
System.out.println (A.I);
A.notify ();
}
System.out.println ("Counter2");
++i;
}

}
}

Class Printer extends Thread
{
Private Storage A;
Public Printer (Storage stor)
{
A = Stor;
}

public void Run ()
{
int i = 0;
while (I < 5)
{
Synchronized (a)
{
System.out.println ("Printer");
try{
A.wait ();
}
catch (Interruptedexception e) {}
System.out.println (A.I);
}
System.out.println ("Printer2");
++i;
}
}
}

After the run,
Try
{
Sleep (100);
}
catch (Exception e) {}
These lines are commented out and look at the running results.

There are two points to say:
(1). If a few threads because of obj.wait () into the hold, then as long as a obj.notifyall () after the execution, they are in a state of operation, but in the end who run first we do not know.

(2). Sleep () and wait () can sometimes perform the same function but note that Thread.Sleep (long a) after a millisecond, the expression can start execution, does not mean that thread is immediately executed. Thread.wait () one but received to Thread.notify () was immediately executed.


6. The ^^ of ...



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.