Java Multithreaded Programming Job summary

Source: Internet
Author: User
Tags jprofiler

I. Multi-threaded KNOWLEDGE summary1. Thread Synchronization

The knowledge about creating threads is not too much to describe. Let's start with the main story and talk about thread synchronization. As with the process synchronization in the operating system, the thread also faces the problem of resource sharing, and how to handle the resource sharing of threads is the most important place to use multithreading. In Java is the introduction of the concept of locking to deal with the relationship between multi-threaded resource competition. The "lock" object can be a block of code, a method, or an object. Once a part is locked, we call that part to acquire the lock. Then, in multiple Java threads, only the thread that owns the lock can run, and the other threads cannot run. If we lock up the code blocks for competing resources, we can avoid conflicts. In the process of using locks, synchronized () is usually used, which means that a block of code is locked. Then we also introduce the following, wait (), and Notifyall (), notify usage. For example, take the multi-threaded elevator as an example, in the multi-threaded elevator input and the relationship between the 1 scheduler. We enter multiple instructions at the same time at one time, and we refer to these instructions as temporary queues. Each time the input instruction is dispatched, each input instruction is added to the total queue. It is not possible to run the scheduler to access the input temporary queue when the input is required, because multiple accesses will cause the input to be dispatched multiple times, and the instruction cannot be written when dispatched because multiple writes will cause the previous input to be rewritten, and the previous input will be ignored. Check the code:

 while  (true   while  (                This . sign!=0) {//  indicates that the queue is not empty  try                  {wait ();                     catch   (interruptedexception e) {                E.printstacktrace (); }}  /**   means middle Process  */  sign  = 1; //          Notifyall (); }    

Two. Three-time operation analysis

2. Multi-threaded Elevator

  Just getting in touch with multi-threading is really tough, and when you just get it, there's no clue. The final result is not very good, but after the debug after the feeling is much better. First look at the results of Jprofiler performance analysis.

Jprofiler Results of performance analysis

The thread that is locked with the wait () method is represented as red, and the CPU is used the most during the input phase, and then three elevators receive instructions and start scheduling. Last input end after input thread ends, and the elevator is not finished. Until it finishes executing. Divided into three stages of the input time will also have the scheduling, so the highest use of the processor, and then three elevators at the same time, the final is an elevator scheduling, you can see three elevators at the same time when the use of the CPU is more than a single elevator scheduling higher. Note that in addition to running threads, the scheduling between CPU processing threads also consumes CPU.

Class Diagram relationships

    1. Thread class: Elevator_run; Input; Super_ride. Where input represents the input thread class, then Elevator_run represents the elevator running thread class, so create three Elevator_run thread classes, then the Super_ride thread class, which represents the dispatch thread class. Threads are parallel, but the thread between input and dispatch must have wait () and notify () relationships to prevent data collisions in the W_legal class from generating an error. At the same time, the Super_ride class and the Elevator_run class share the resource elevator class, so elevator cannot be called when Super_ride calls Elevator_run, so Elevator_ When run calls elevator, super_ride cannot be called, so use synchronized () in these two threads to implement thread synchronization.
    2. About the elevator class, I will lift class as a class, only includes the elevator properties and a method, and then the elevator run as a class, Elevator_move class, modified class contains all the methods of elevators, as well as the calculation of time. In the Elevator_run thread, pass the constructor method into the elevator class and build a new object for the Elevator_move class.
    3. On the scheduling class, the scheduling method is not directly implemented in the Super_ride, I also wrote a special responsibility for scheduling classes, including the scheduling of the properties and methods. When scheduling, first in the super_ride through the construction method into the elevator and instructions, and then instantiate a scheduler, the elevator and the temporary queue into the scheduler, you can get each elevator queue.
Sequence Diagram Analysis

Metric analysis

3. File Systemabout IFTTT

Https://en.wikipedia.org/wiki/IFTTT, or, Https://baike.baidu.com/item/ifttt/8378533?fr=aladdin, and IFTTT ability is also a very powerful app, we can go to try, https://ifttt.com/products.

Jprofiler Results of performance analysis

As for this test, the test files are not many, so the CPU usage is relatively low. I can clearly see that there is a problem, that is not always monitoring files. And then I'll explain. One input adds a thread, which means that each file corresponds to a monitoring thread that is used to monitor the file changes in real time. For why the thread end is because, in my program, the monitoring file will only monitor a change, but the monitoring directory will monitor multiple changes. The reason is explained in the Class Diagram section. The start phase of CPU usage increases primarily when input is needed to create threads.

Class Diagram Description

This time the class diagram is obviously quite chaotic

  1. With regard to thread classes, there are mainly modified,path_changed,renamed,size_changed,test_thread of five thread classes. The first four threads do not start to start, only the input of a valid monitoring object, and the monitoring process will create a corresponding monitoring thread. Then the test_thread is the thread used for the test.
  2. About the monitoring file class, when monitoring the file, if it is a monitoring directory, then each file change in the directory will trigger the monitor. And after the file changes in the directory to continue to monitor, I realized the way is to first build a File_all class;
    class File_all {protected String name=null;     protected long f_l=0;      protected long l_t=0;      protected String path=null;}

    Since the file method returns a pointer to a document, the return value changes when the path changes, so the File_all function is to save the properties of the file before the path changes, used for comparison after the file changes. So how do you get all the files in the entire directory? A recursive search method is of course used.

    classTest {protected voidTest (String Filedir, arraylist<file_all>fileList) {        //= new arraylist<file_all> ();File File =NewFile (Filedir); file[] Files= File.listfiles ();//get all files or folders under the directory        if(Files = =NULL) {//If the directory is empty, exit directly            return ; }        //iterate through all the files in the directory and save the file attributes.         for(File f:files) {file_all tem_file=NewFile_all (); if(F.isfile ()) {Tem_file.file=F; Tem_file.name=F.getname (); tem_file.f_l=f.length (); tem_file.l_t=f.lastmodified ();            Filelist.add (Tem_file); } Else if(F.isdirectory ()) {Test (F.getabsolutepath (), fileList); }        }        return ; }}

  3. We'll pass a ArrayList of File_all into the method test, and then we can call the method to get FileList, which is the dynamic array that stores all the file properties.
  4. So if two threads are monitoring the same file will there be a problem of resource competition? The answer is yes, because assuming thread 1 is monitoring the file under a path, the renamed then recover is monitored. Thread 2 monitoring is also a path under the file, monitoring is modified then details, so the stake Oh Thread 1 run first, then thread 1 has not recover a path under the file, Threads 2 will get the wrong result, found no files. I used the workaround is to lock the file method, but will only lock Size_changed, and renamed two threads in the file changes, so when monitoring the same file, if there is a renamed situation will be run after the operation of the next thread.
  5. The implementation of the snapshot, did not carefully read the instructions, completely according to their own ideas, no snapshot concept, only know the need to compare the differences between the two files before and after the comparison method, pseudo-code as follows:
    if(File_2.isdirectory ()) {chose= 0; ArrayList<File_all> FileList =NewArraylist<file_all> ();//new filelist to store old filesTest_sc.test (obj_path,filelist);//recursively gets the old file attributes and stores             while(true) {ArrayList<File_all> FileList2 =NewArraylist<file_all> ();//Create new FileTest_sc.test (OBJ_PATH,FILELIST2);//recursively gets the new file attributes and stores                /**various operations*/filelist.clear (); //After the various comparison operations, that is, after comparing the old and new files, empty the old and new filesfilelist2.clear ();    Test_sc.test (obj_path,filelist); //get old files again, store old files, and compare them later                Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }            }        }
Sequence Diagram Analysis

Metric analysis

The results of the metrics analysis show that the code is still vulnerable.

4. Results of taxi jprofiler performance analysis

Taxi test, I used a one-time input a large number of requests. From a few peaks of the CPU run, the first is the program start, create 100 taxi threads, you can see that the creation of the thread is CPU-intensive, and then every input, each time the input is more CPU-intensive, because each input or build a scheduling thread, also need to create multiple threads, Results in a significant increase in CPU operation. There will be some minor spikes in the middle, which is the taxi run.

Class Diagram Analysis

  1. Thread class: Actually only scheduler and Taxi_move, and one of the input is written before, the program did not use, forget to change, also did not delete, and then was reported a design flaw, ..., this is the time of the submission of the class diagram, so input is still in the Taxi_ The move thread is the thread that represents the taxi run, and 100 taxis have 100 taxi_move threads, and the taxi_move thread is mostly a taxi run. While the scheduler thread is the scheduler thread, when the thread is created in the request class, each valid input creates a dispatch thread, within 3s, if there is a car, then complete a dispatch, and then by changing the properties of the taxi, taxi_ The move thread will let the taxi run in a certain way. So a taxi is a competitive resource for taxi_move threads and scheduler threads? Nor is it entirely because the scheduler will not dispatch the running state of the car, while the Taxi_move will only dispatch the running state of the car.
  2. Call the GUI, about how to display a taxi on the GUI? Of course, every time the taxi status changes, the location of the taxi is refreshed.
  3. The shortest path, the random path to the taxi while wandering, is in the taxi class. Gui.java provides a way to find the shortest path, perhaps some students will use the Guiinfo class distance method, but carefully to see, where d[][] is a property of the Guiinfo class, then we can directly through the POINTBFS (root) method , the shortest path to root is obtained at any point, and then the path exists in d[][], which greatly reduces the computation time of the shortest path. Students with real time can do this, but the next use of the fake time do not have to care too much. About random paths,
     while(true) {Direction= (int) (1+math.random ());//randomly select a location            if(Direction==1 && This. location_x<79 && Map_mess.graph[location][location_1]==1) {                 This. location_x = This. location_x+1;  Break; }            Else if(direction==2 && This. location_x>0 && Map_mess.graph[location][location_2]==1) {                 This. location_x = This. location_x-1;  Break; }            Else if(Direction==3 && This. location_y>0 && Map_mess.graph[location][location_3]==1) {                 This. location_y = This. location_y-1;  Break; }            Else if(Direction==4 && This. location_y<79 && Map_mess.graph[location][location_4]==1) {                 This. location_y = This. location_y+1;  Break; }        }

    Because it is connected diagram, there is always a way to go.

Sequence Diagram Analysis

You can see the relationships between the classes

Metric analysis

The first lap of complexity clearance, is not very happy, but this is actually false. After many tests, I found the problem, the real situation is this:

But the reason is, I was too anxious, the first picture is not fully tested the situation has not fully demonstrated the cyclomatic complexity.

three. Second Assignment summarySome thoughts on multi-threaded programming
    1. Thread synchronization: I don't know if my idea is right, but from the multi-threaded elevator, I think so, all the resource competition is the relationship between producers and consumers. Of course, there will be two roles for the same class, and it will be more complicated to analyze.
    2. The end of the thread, in the multi-threaded elevator There, I did not handle the end of the elevator thread, because in many cases we use while (true) to run the thread, it is easy to cause this, so the necessary markup is very important.
Experience

Frankly speaking, I actually every homework is holding, as long as effective on the idea of writing, so the last write is not particularly good, this three weeks really is very difficult ah. The first week when the thought of a word: "No pains, no Gains". Bite the teeth again, the next week when the thought of a sentence "If one day, you feel that life is so difficult, it may be the harvest will be very huge." The second week, the third homework is quick to give up, life is important ah, later still bite teeth insisted on down, because again think of a word "future you, will thank you so hard now." In this very difficult day, I can only rely on these chicken soup to live. So I want to share with you, to "dry this bowl of chicken soup."

Java Multithreaded Programming Job summary

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.