Java 11th time Job

Source: Internet
Author: User

I. Summary of this week's study

1.1 Summarize multithreading related content in the way you like (mind map or other).

Two. Written work

Multi-thread of this PTA job title set

1. Source code reading: Multi-threadedBounceThread1.1BallRunnableWhat is the use of classes? Why do I need to call in codeThread.sleepTo hibernate?

A: The Ballrunnable class is a multi-threaded class that opens a program that moves the ball in accordance with the specified rules and then draws it to get the shape of the ball. The code calls to Thread.sleep hibernate in order to delay the completion of the thread time, so that we can see the movement of the ball, or too fast to see the movement of the ball track.

1.2 Questions: a)Ball.javaOnly two things were done, what were the two things?

A: move() method, to achieve the movement of getShape() small balls, methods, to obtain the ball's coordinates and size.

bBallComponentWhat does the object do?

A: Add a small ball, draw a small ball.

c) What is the use of the internal ArrayList?

A: Used to store the added ball.

d) How many ballcomponent objects have been generated during the program's operation?

A: only 1.

e) The program uses multithreading techniques, each of which is drawn in separate threads?

answer : Yes. Each time you press a start button, the addBall method starts a new thread.

2. Experimental Summary: Title set (Multithreading) 2.1 Topics: Thread, Printtask, runnable, and anonymous inner classes. and answer: a) by definingRunnableInterface implementation class to implement multithreaded programs than by inheriting from theThreadWhat are the benefits of class implementation of multithreaded threads?

Answer: Multiple inheritance is not supported in Java, only one parent class can be inherited, but multiple interfaces may be inherited, so the method of implementing the interface can avoid the limitation of inheritance. Using runnable to implement multithreading enables multiple threads to complete multiple tasks together.

b) 6-1,6-3,6-11 experimental summary.
    • 6-1: When the thread is constructed, the number of times to loop will be passed in. Then rewrite the run () method. Finally, System.out.println(Thread.currentThread().getName()+" "+isAlive()) Print identification information is used.
    • 6-3: starts a thread T1 in the main method, which prints 3 lines of information: the main thread name, thread name T1 threads, threads T1 all interfaces implemented by the thread, using System.out.println(Arrays.toString(getClass().getInterfaces())); printing.
    • 6-11: The main problem is to write the PrintTask class implementation Runnable interface, the main function is to output an integer from 0 to N-1 (n is PrintTask initialized when the object is created). and the output identity information is used at the end System.out.println(Thread.currentThread().getName()); .
2.2 Using a lambda expression to overwrite 6-3
Thread t1 = new Thread(        () -> {            System.out.println(mainThreadName);            System.out.println(Thread.currentThread().getName());            System.out.println(Arrays.toString(Thread.class.getInterfaces()));        });
2.3 Title: 6-2 (runnable and stop thread). Answer: How do I need to properly stop a running thread?
    • 6-2: The main focus of this topic is the contents of the run () method. Check only once for each incoming word (and then set Word to NULL when you are finished checking). After jumping out of the infinite loop, use the System.out.println(Thread.currentThread().getName() + " stop") print identity information.
    • A : A Boolean variable is generally used to terminate a thread. Use the While statement to exit the loop in order to reach the stop thread by changing the Boolean tag value in the run.
3. Mutex Access 3.1 modificationsTestUnSynchronizedThread.javaThe source code allows it to be accessed synchronously. (Key code, need to appear number)

As follows:

4. Mutually exclusive access and synchronous access

Complete episode 6-4 (mutually exclusive access) with 6-5 (synchronous access)

4.1 In addition to usingsynchronizedModified method to implement mutually exclusive synchronous access, what else can be usedsynchronizedImplementation of mutually exclusive synchronous access, using code descriptions (please show the relevant code and number)?
  • You can use synchronized code blocks:

    public static void addId() {//黄子颖 201621123045synchronized (Counter.class) {//代表Counter类型的对象    id++;}}
  • Use explicit Lock and Condition objects:

      class Account {//Huang 201621123045private int    Balance;public account (int balance) {super (); This.balance = balance;} public int getbalance () {return balance;}    public void Deposit (int. money) {Lock.lock ();        try {balance + = money;    Condition.signalall ();    } finally {//Todo:handle finally clause lock.unlock ();    }}public void Withdraw (int money) {lock.lock ();            try {while (Balance < money) {try {condition.await ();            } catch (Interruptedexception e) {throw new RuntimeException (e);    }} Balance-= money;    } finally {//Todo:handle finally clause lock.unlock (); }}private Java.util.concurrent.locks.Lock Lock = new Java.util.concurrent.locks.ReentrantLock ();p rivate Java.util.concurrent.locks.Condition Condition = Lock.newcondition ();}  
4.2 What is the difference between a synchronous code block and a synchronization method?
    • Synchronous methods use adornments directly on methods synchronized to implement locks, while synchronous code blocks use synchronized code blocks internally.
    • Synchronous code blocks perform better, but the range of synchronization methods is larger.
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. When the program executessynchronizedHow does the state of a thread change when synchronizing a block of code or a synchronous method?

A : the principle is that when a resource is used by a task, it is locked. Now the task that accesses a resource must lock the resource, and other tasks cannot access it. When it is unlocked, another task can lock and use the resource. For example: in the following code snippet, you can get an internal lock on the object "this". When executing a program, if you cannot get a corresponding object lock, you will not be able to execute the contents of the above code block, that is, the i++ statement in the synchronized synchronization code block, you must wait and wait for the object lock. This enables mutually exclusive access through object locks.

class MyCounter{   private int i = 0;   public void increment(){           //i++;           synchronized (this) {        i++;           }   }    ……}

The state of the thread changes to: If the object lock is not obtained, enter the look pool state, wait for the synchronization lock to be released, and after the synchronization lock is released, the thread enters the runnable state.

4.4 What keywords are used in Java Multi-threading to implement communication between threads, so that threads work together?

Answer: Java Multi-Threading uses wait() and notify() / notifyAll() methods to implement the communication between threads, in order to achieve the collaborative work of threads.

5. Collaboration between Threads: Producer consumer issues 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?

The results of the operation are as follows :


A : The result may not be normal, the remaining goods may not be 0, may be the other quantity. Because of the inconsistent access speed of producers and consumers, there may be situations in which goods are being taken without stock.

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

As follows:

6. Object-oriented design job-Library Management System 6.1 system of the functional modules table, the table reflects the owner of each module. 6.2 Run the video 6.3 Explain the module you are responsible for, and paste the key code of your own module (the number and name appears). Three. Code Cloud and PTA

Topic Set: Multithreading

3.1. Code Cloud codes Submission record

In the Code cloud Project, select statistics-commits history-set time period, and then search for and
Several elements must appear: Submit Date-user name (name and school number)-no instructions

3.2 "Multi-threaded" PTA Submission List

Two graphs are required (1. Ranking chart. 2.PTA Submission list diagram)


3.3 Count the amount of code completed this week

The weekly code statistics need to be fused into a single table.

Week Time Number of rows number of new rows Number of files number of new files
1 115 115 17 17
2 421 306 24 7
3 698 277 30 6
5 1085 387 38 8
6 1497 412 48 10
7 2033 536 57 9
8 2265 232 60 3
9 2728 32t 65 5
10 3360 632 73 8
11 3958 598 83 10
12 4435 477 90 7

Java 11th time Job

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.