JavaSE review 4

1. Multithreading

Threads and processes each have pros and cons and what difference it?

  • The process is the smallest unit of resource allocation, the thread is the smallest unit of program execution.

  • Process has its own separate address space, each started a process, the system will allocate address space for it, set up a data table to maintain the code segment, stack and data segments, this operation is very expensive. The thread is a shared process data, using the same address space, so the CPU changes than the process takes a much smaller thread, while creating a thread overhead is much smaller than the process.

  • More convenient communication between threads, the thread in the same process share global variables, static variables and other data, and communication between processes carried out in a manner (IPC) communication. But how to handle the synchronization and mutual exclusion is the difficulty of writing multithreaded programs.

  • But the program more robust multi-process, multi-threaded program as long as there is a thread dies, the whole process is dead, too, and a process dies the other will not have impact on the process, because the process has its own separate address space.

Thread multi-threaded :

By enabling multiple threads must use the thread in the start function.

runnable multi-threaded (avoid the limitations of single inheritance) :

runable is the interface, you can achieve multiple inheritance, but did not start method, so I can not just start a thread, but the thread constructor can be runnable as a parameter, so it can be passed via the constructor.

Mythread which implements runnable interface. After the multi-thread priority runnable.

The relationship between the thread and Runnable :

View source code:

We found runnable thread class implements an interface, inherited when the thread class before actually overwritten or runnable in the run method. And after performing start actually calls the run method, a map showing the relationship between the runnable and thread:

The thread started making calls when multithreading is the start method, and then find that the run method.

当通过thread类的构造方法传递了一个runnable的接口对象的时候,那么该接口对象将被thread类中的target属性所保存。在thread中调用start方法时会调用下面的run方法:

而这个覆写的run方法会调用runnable接口子类(上面图中的new Mythread对象,这个对象实现了runnable接口)被覆写过的run方法。

当有多个线程时的结构:

在实际情况下这里的线程对象就可能是各个用户。

模拟多个用户买票的程序:

内存如下图所示:

 

Guess you like

Origin www.cnblogs.com/ljq2622/p/11104593.html