Study Number: 201621123032 Java programming 11th Week of study summary

Source: Internet
Author: User
Tags mutex thread class

1: Summary of this week's study 1.1.: Summarize multithreading related content in the way you like (mind map or other).

2: Written assignment 2.1.: Source code reading: What is the use of multi-threaded bouncethread1.1:ballrunnable classes? Why do I need to call Thread.Sleep to hibernate in my code?

The Run method in the Ballrunnable class loops through the move function and the repaint function to draw the moving trajectory of the ball. Thread.Sleep is used to hibernate the thread.
Sleep is to allow us to see the movement of the ball, or the program will be completed soon, we have no way to observe the movement of the ball path.

1.2:ball.java only did two things, what are the two things? What does the Ballcomponent object do? What is the use of the ArrayList inside? How many ballcomponent objects are generated during the program run? The program uses multithreading techniques, each of which is drawn in separate threads?

Two things:

    • The move function is the way the ball moves.
    • The Getshape function is the coordinate that returns the ball.
      The Ballcomponent object is used to add a small ball, and the inner ArrayList is used to store the newly added ball. 1 Ballcomponent objects were generated during the run of the program. Each ball is drawn in its own line thread.

      2.2.: Experimental Summary: Title set (multithreading) 2.1: Title: Thread, Printtask, runnable, and anonymous inner class.

      and answer: A) What is the benefit of implementing multithreaded programs by defining the implementation class of the Runnable interface than by inheriting from the thread class? b) 6-1,6-3,6-11 experimental summary.
      A: A class can inherit only one parent class, and there are limitations. and a class can implement multiple interfaces, when implementing the Runnable interface to call the thread's thread (Runnable Run) construction method to create a process, using the same Runnable instance, the established multi-threaded instance variable is also shared But by inheriting the thread class, you cannot establish multiple threads with one instance.

B:

    • 6-1: Writing the Mythread class inherits from thread and implements the print function in the Run method
    • 6-3: Multithreading using anonymous inner classes can inherit the thread class to implement multi-threading, or you can implement the Runnable interface, create multithreading, and start. Also note that the main thread name is mainthreadname, thread T1 thread name is Thread.CurrentThread (). GetName ()

    • 6-11 different from the first question of the inheritance tread class, I used to implement the Runnable interface method. The Runf method is the same as the first question.

2.2.: Overwrite 6-3 with lambda expression

2.3: Title: 6-2 (runnable with Stop thread). Answer: How do I need to properly stop a running thread?

There are 3 ways to terminate a running thread in Java:
Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the Run method completes.
Use the Stop method to forcibly terminate, but this method is not recommended because stop and suspend and resume are obsolete methods.
Use the interrupt method to break the thread.

2.3: Mutex Access 3.1: Modify the Testunsynchronizedthread.java source code so that it can be accessed synchronously. (Key code, need to appear number)
//201621123032//王彩云class Counter {    private static int id = 0;    public static synchronized void addId() {        id++;    }    public static synchronized void subtractId() {        id--;    }    public static int getId() {        return id;    }

Operation Result:

2.4: Mutually exclusive access and synchronous Access 4.1: In addition to using the synchronized adornment method to achieve mutually exclusive synchronous access, what else can use synchronized to achieve mutually exclusive synchronous access, using code description (please show the relevant code and number)?

4.2: What is the difference between a synchronous code block and a synchronization method?

The synchronous code block is locked inside the method, and the synchronous method is added synchronized on the method directly, the range of the synchronous method lock is larger, and the synchronization code block range is smaller, the larger the general synchronization range, the worse the performance.

4.3: What is the principle of implementing mutually exclusive access? Use the object lock concept and describe it in conjunction with the corresponding code block. How does the state of the thread change when the program executes the synchronized synchronous code block or synchronous method?

Each object in Java has a lock that, when accessed by the synchronized method of an object, means that the object is locked, and no other thread can access the Syncronized method until the previous thread executes the method. Other threads will be able to access the Synchronized method.

class test implements Runnable{    public int a;    public void run() {        synchronized(this) {            a++;            try {                        System.out.println("当前线程---"+Thread.currentThread().getName()+"---a--"+a);            Thread.sleep(5000);            }catch (InterruptedException e) {                e.printStackTrace();            }        }    }    }public class boketest {    public static void main(String[] args) {        test sc=new test();        test sc1=new test();        Thread th1=new Thread(sc);        Thread th2=new Thread(sc);        th1.start();        th2.start();    }

Operation Result:

The second line results in a interval of 5 seconds to print, because synchronzied implements the mutex, and only the SC object lock, so when the first thread locks the SC, and the second thread is also through the SC to access the Run () method, Therefore, you must wait until the first thread finishes executing the object's methods to obtain an object lock. Therefore, a second thread must be executed in 5 seconds

4.4:java What keywords are used in multi-threading to implement the communication between threads, and to achieve the collaborative work of threads?

Use the Wait (), notify (), and notifyall () keywords to implement communication between threads, which in turn enables threads to work together.

2.5: Collaboration between threads: Producer Consumer Issue 5.1: Run Myproducerconsumertest.java. The result of the normal operation should be 0 goods left in the warehouse. Run multiple times, observe the results, and answer: Is the result normal? What's not normal? Why?

Not normal. Running results Sometimes the remaining cargo in the warehouse is 0. This is because there is no cooperation between the threads and there is an inconsistency between supply and demand.

5.2: Use synchronized, wait, notify solve the problem (key code, need to appear number)

Code modification:

//201621123032    //王彩云    public synchronized void add(String t) {                if (repo.size() == capacity) {            try {                wait();            }catch(InterruptedException e) {                e.printStackTrace();                            }        }        if (repo.size() >= capacity) {            System.out.println("仓库已满!无法添加货物。");        } else {            repo.add(t);        }        notify();    }    public synchronized void remove() {        if (repo.size() == 0)            try {                wait();            }catch(InterruptedException e) {                e.printStackTrace();                            }                    if (repo.size() <= 0) {            System.out.println("仓库无货!无法从仓库取货");        } else {            repo.remove(0);        }        notify();    }

Operation Result:

2.6: Object-oriented design job-Library management system (before the end of the subject) 6.1: The System Function module table, the table reflects the owner of each module. 6.2: Run Video 6.3: Explain the module you are responsible for, and paste the key code of your own module (the number and name of the school). 3: Code Cloud and PTA3.1: Code cloud codes Submission record

3.2: "Multi-threaded" PTA Submission List


3.3: Count the amount of code done this week
Week Time Total code Amount new increase in code volume Total Folder Add new Folder
1 114 114 11 11
2 520 50W 16 6
3 1089 569 22 6
5 1425 336 29 7
6 1819 394 31 2
7 2987 1168 54 23
8 5437 2450 79 25
9 5695 258 84 5
10 6680 985 102 18
11 6935 255 111 9
12 7401 466 123 12

Study Number: 201621123032 Java programming 11th Week of study 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.