Chapter X Multithreading

1. The program, what is the difference between processes, threads that? To give realistic examples illustrate. (Online information, with the teacher's
not the same)


Program (Program): is a set of instructions. Program can not be executed independently, only to be loaded into memory to perform the system allocates resources for it.
Process (Process): As noted above, the implementation of a program called process.
Process is an independent unit of resource allocation system, each process occupies a particular address space.
Program is static text description of the process, the process is dynamic activities program order execution within the system.
Thread (Thread): a "single continuous flow of control" process.
CPU thread scheduling and allocation is the basic unit is smaller than the basic unit of the process can be run independently, also known as lightweight process.
Thread can not exist independently, it must be attached to a process. A process can include a plurality of parallel threads, one thread is certainly a part of the process. Java Virtual Machine allows an application to concurrently execute multiple threads.

For example: If a workshop is a program, an ongoing task workshop production is a process, each worker engaged in different jobs in the workshop is a thread.


2. [machine] create multi-threaded Java classes in what way? Were used code description. And call it.


(1) custom thread class that inherits the Thread:
public class MyDefinedThread the extends the Thread {
// override the run () method;
public void run () {
// put thread needs to perform tasks written on the run () method in;
}

static void main public (String [] args) {
MyDefinedThread MyDefinedThread new new MDT = ();
mdt.start (); // start threads.
}
}
(2) custom class that implements Runnable interface;
public class MyRunnable the implements Runnable {
// implement run () method;
public void run () {
// the thread needs to perform tasks written in run () method in;
}

static void main public (String [] args) {
MyRunnable new new MyRunnable of Mr = ();
Thread TH = new new Thread (of Mr); // "of Mr" is not a thread object, but to be passed as an argument to the constructor Thread in; "th" is a thread object.
th.start; // start the thread.
}
}


3.Thread class has not implement Runnable?


It has achieved.


4. When the start method is called a thread object, the thread begin to run it?


Not only enter the ready (operable) state, waiting for allocation of CPU time slice. Once CPU time slice, i.e. enters the running state.

The following code, in fact, there are several threads running:


Two: threads t and main () method (the main thread).
static void main public (String [] argc) throws Exception {
the Runnable new new = R & lt Thread6 ();
the Thread the Thread new new T = (R & lt, "the Name Test");
t.start ();
}

6. talk about: the difference between sleep, yield, join methods.


sleep (): thread to be suspended within the specified time, into the blocked state.
Ready state after a specified time arrives. Thread calls sleep () method, freeing the CPU when not release the object lock (if holding an object, then lock).
join (): the current thread waiting threads calling this method ends before proceeding. Such as: call the main method t.join (), that the main method to enter the blocked state at this time, such as t-threaded execution has been completed, the main method and then return to the ready state, ready to continue.
yield (): This method of calling thread pause and return to the ready state. So be executed immediately after calling the method of the thread is likely to enter the ready state.


7. Why does not recommend the use of stop and destroy methods run to the end of the thread?


stop (): This method may be forced to suspend a running thread or suspended. But stop unsafe methods, like forcibly cutting off power to the computer, rather than the normal shutdown procedure. It may produce unpredictable results. For example:
When you call stop on a thread object () method, the thread object thread will stop running immediately and throw specialized ThreadDeath () exception. Here "immediately" too "immediately", and
if a thread is executing:
the synchronized void {
X =. 3;
Y =. 4;
}
Since the method is synchronous, multiple threads accessing always guarantee x, y are simultaneously assigned and if a thread is executed to x = 3; when invoked by the stop () method, even in a sync block, to stop it altogether, and thus creating a crippled incomplete data. The multi-threaded programming in the most basic conditions to ensure the integrity of the data, so please forget to stop the thread method, since we could not say "stop thread" was.

destroy (): This method was originally designed to destroy this thread without any resources released. It held any monitor will remain locked. However, this method will never be realized. Even if you want to achieve, it is also very likely to suspend () mode is deadlocked. Keeping a lock to protect critical system resources if the target thread is destroyed, any thread can access this resource again at any time. If another thread ever attempted to lock this resource, deadlock occurs.


[8] to write machine code instructions, a typical embodiment of the thread terminates.


(1) When the run () method executed, the thread is automatically terminated.
(2) However, sometimes run () method does not end (e.g., the server side listener), or other tasks needed to process the loop. In this case, generally these tasks in a cycle, such as a while loop. If you want the loop runs forever, you can use while (true) {......} to deal with. But to make a while loop exits under a certain condition, the most direct way is to set a boolean flag, and by setting this flag to true or false to control whether the while loop exits. Now be described by way of example:

public class ThreadFlag extends Thread 

    public volatile boolean exit = false; 

    RUN void public () 
    { 
        the while (Exit!); 
    } 
    public static void main (String [] args) throws Exception 
    { 
        ThreadFlag new new Thread ThreadFlag = (); 
        Thread.start (); 
        SLEEP (5000); delay // main thread 5 seconds 
        thread.exit = true; // terminate the thread the thread 
        Thread.join (); 
        System.out.println ( "thread exits!"); 
    } 

In the above definition code of an exit sign exit, when the exit is true, while loop exits, exit the default value is false. When defining exit, using a Java keyword volatile, the purpose of this keyword is to synchronize the exit , that can only be modified by a thread exit value at the same time.


9.A priority thread is 10, B-priority thread is 1, then when scheduling will call it A?


Not necessarily. Thread priority may have different meanings for different thread scheduler, users may not be intuitive guess.


[10] machine to imitate the teacher classroom example, complete the simulation operation code account to withdraw money.


Before 11.synchronize modification method What does it mean?


Only one thread enters the method, another thread in order to call the method at this time, only to wait in line, the current thread (the thread is inside the synchronized method) After carrying out the method, other threads to enter.


12.synchronize modified statement block, as the following code. Is a block of code that must be run when
the lock object account. If you do not get, what will happen?


If you do not get the lock account object, you can not synchronize the implementation of the modified block of statements, including the statement block, there are other synchronized block and synchronization method to perform the object lock this account of need.
the synchronized (Account) {
IF (account.money-drawingNum <0) {
return;
}
}

13. [machine] deadlock is caused by how? Express in words. Write a code example.


Excessive thread synchronization causes a deadlock. If both threads are waiting for each other to release a lock in order to proceed, sometimes there will be a stalemate: two threads holds a lock on the other side needs, and two threads need each other to release a lock in order to continue operation. for example:

Let's look at an example of such a life: there is a bridge over a river, the bridge is narrow, can only accommodate a car through, you could not get two cars in parallel. If you have two cars A and B, respectively, onto the bridge from opposite ends of the bridge, then for A car, it traveled section of the road bridge on the left (ie, possession of part of the resources of the bridge), but also in order to cross the bridge B must wait for the car to make a bridge to the right, in which case a car can not move forward; for the B car, it traveled section of the road on the right deck (ie possession of part of the resources of the bridge), in order to cross the bridge must wait a car make a bridge to the left, then B car can not move forward. Both sides of the car are not reversing, resulting in wait for each other to make a bridge, but who does not give way, it will wait endlessly. This phenomenon is a deadlock. Deadlock is a problem of the program is running, it is to be avoided.

代码示例:
publicclass DeadLock{
Object A=new Object();
Object B=new Object();

publicvoid toEast(){
synchronized(A){
synchronized(B){
System.out.println("向东行驶。");
}
}
}
publicvoid toWest(){
synchronized(B){
synchronized(A){
System.out.println("向西行驶。");
}
}
}
}
publicclass ToEastThread extends Thread {
DeadLock d=new DeadLock();
public ToEastThread(DeadLock d) {
super();
this.d = d;
}
publicvoid run(){
d.toEast();
}
}
publicclass ToWestThread extends Thread {
DeadLock d=new DeadLock();
public ToWestThread(DeadLock d) {
super();
this.d = d;
}
publicvoid run(){
d.toWest();
}
}
publicclass Test1 {
publicstaticvoid main(String[] args) {
DeadLock d=new DeadLock();
ToEastThread et=new ToEastThread(d);
ToWestThread wt=new ToWestThread(d);
et.start();
wt.start();
}
}


14. Use Timer TimerTask realization timing and execution timing executed at 17:00 pm every day.

Introduction of Knowledge points:
(1) the Timer: timer, in fact, threads, time scheduling TimerTasks have.
(2) TimerTask: run method of a class has, the code needs to put the timing of execution run vivo. TimerTask general is creating an anonymous class way.
Syntax Description:
java.util.Timer timer = new new java.util.Timer (to true);   
// to true illustrate the timer run in daemon mode (low priority,   
// end of program timer also automatically end), attention, javax.swing   
// package also has a Timer class, if the import of used swing bag,   
// pay attention to the name of the conflict.   
= New new Task the TimerTask the TimerTask () {   
public void RUN () {   
... // code that need to be performed each time put there.   
}   
};  
Usage Description:
Method // following are some of the scheduled task:   
 timer.schedule (task, Time);   
// type Date Time: executed once at the specified time.   
 timer.schedule (Task, firstTime, period);   
// firstTime type Date, Long period of   
// firstTime time from the start, every period msec.   
timer.schedule (Task, delay)   
// delay type long: From now through a delay milliseconds   
timer.schedule (Task, delay, period)   
// delay is long, period is long: from now through the delay milliseconds after every period   
executed once // milliseconds.  
For example:
Import java.util.TimerTask;
publicclass TimePrintTask the extends the TimerTask {
int I =. 1;
publicvoid RUN () {
System.out.println (I);
I ++;
}
}
publicclass the Test {
publicstaticvoid main (String [] args) {
the Timer new new = the Timer Timer ();
//timer.schedule(new TimePrintTask (), 1000, 500);
DateFormat new new DF = the SimpleDateFormat ( "YYYY / the mM / dd HH: mm: the SS SS");
a Date firstDate = null;
the try {
firstDate = df.parse ( "2016/12/09 17:00:00 00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.schedule(new TimePrintTask(),firstDate , 1000);
}
}

15.wait method is called, where the thread is held by the lock release resources? Sleep way to do that?


wait: the release of CPU, the lock is released;
SLEEP: release CPU, does not release the lock.


16.wait, notify, notifyAll method is defined in the Object class do? What role are? wait (), notify (), notifyAll () does not belong to the Thread class, but belong to the Object class, which means that each object has a wait (), notify (), notifyAll () function. Each object has a lock because the lock is on the basis of each image, and wait (), notify (), notifyAll () are associated with the lock method.

The role of three methods are:
the wait: causes the current thread to wait to enter the block until another thread invokes the object's notify () method or the notifyAll () method. The current thread must own this object's monitor (Object lock). The thread releases ownership of this monitor and waits until another thread by calling the notify method or the notifyAll method notifies threads waiting on this object's monitor to wake up. The thread will wait until then to regain ownership of the monitor in order to proceed.
The Notify: wake up a single thread on this object's monitor (Object lock) to wait. If all threads are waiting on this object will be selected wake up one thread. Until the lock on this object for the current thread to give up, to continue with the thread to be awakened. This method should only be used as the owner of this object monitor thread to call.
"The current thread must own this object's monitor" and "This method should only be used as a thread of this object's monitor to call the owner," explained wait method and notify method must be performed within a sync block, i.e. synchronized (within the obj).
notifyAll: wake up all monitor threads on this object (Object lock) waits.


17.notify where the object is to awaken wait first thread pool in it?


No. Call to notify () method results in unblocking threads from calling this object's wait () method obstruction thread randomly selected, we can not predict which thread will be selected.

18. [machine] using threads of communication to achieve producer - consumer issues.

See class instance.

Guess you like

Origin www.cnblogs.com/ren549047861/p/11294158.html