1. This week's learning summary

1.1 In the way you like ( Mind mapping or something ) Summarize the related content of multithreading .

Multithreading :

  • There are two confusing concepts about the operating system , Processes and threads .

process : A running example of a computer program , Contains instructions that need to be executed ; It has its own independent address space , Contains program content and data ; The address spaces of different processes are isolated from each other ; Processes have all kinds of resources and state information , Include open files 、 Subprocess and signal processing .

Threads : Represents the execution flow of a program , yes CPU The basic unit of scheduling execution ; Threads have their own program counters 、 register 、 Stack and frame . Threads in the same process share the same address space , Share the memory and other resources owned by the process lock at the same time .

  • Java The standard library provides process and thread related API, The process mainly includes the java.lang.Process Class and create process java.lang.ProcessBuilder class ;

    Representing threads is java.lang.Thread class , After the virtual machine starts , Usually only Java Class main Method this normal thread runs , The runtime can create and start new threads ; There's another kind of daemons (damon thread), The daemons run in the background , Provide the services needed for the program to run . When all threads running in a virtual machine are daemons , The virtual machine stops running .
  • Visibility between threads : Modification of shared data in a process by a thread , Is visible to another thread .

2. Written work

This time PTA The problem set is multithreaded

1. Exclusive access and synchronous access

Complete the problem set 4-4( Exclusive access ) And 4-5( Synchronous access )

1.1 Besides using synchronized Modify method to achieve mutually exclusive synchronous access , What other way to achieve mutual exclusive synchronous access ( Please show the relevant code )?

  • Use to Lock Objects and Condition object .
  • The code is as follows :
public void deposit(int money) {// synchronized
lock.lock();
try {
balance += money;
plus.signalAll();
} finally {
lock.unlock();
}
}
public void withdraw(int money){
lock.lock();
try{
try{
while(this.getBalance()<=0)
condition.await();
condition.signal();
}catch(Exception e){
System.out.println(e);
}
this.balance=this.getBalance()-money;
if(balance<0)
throw new IllegalStateException(balance+"");
}finally{
lock.unlock();
}
}

1.2 What's the difference between synchronous code blocks and synchronous methods ?

  • difference :
  1. The scope of synchronization method lock is relatively large , The scope of synchronous code block is smaller .
  2. The synchronization block needs to indicate the lock object , The synchronization method is locked by default this.
  3. In terms of performance , It's better to use synchronous blocks to reduce the locking range and improve the concurrency efficiency .

1.3 What is the principle of mutually exclusive access ? Please use the concept of object lock and the corresponding code block to explain . When the program is executed synchronized When synchronizing code blocks or methods , How the state of a thread changes ?

  • The principle of mutually exclusive access : Each object has one monitor( Lock mark ).
  • use synchroined Examples of keyword modification methods :
 public synchronized void duixianglock()
{
System.out.println("duixianglock---in");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("duixianglock---out");
}
  • Lock a task when it is executed , Other objects cannot be used until they are unlocked , The pattern of one object carrying on one resource .

1.4 Java What keywords are used in multithreading to achieve communication between threads , And then realize the cooperation of threads ? Why synchronous access is usually placed in synchronized Method or code block ?

  • In general use wait() Key words and notify() Keyword to implement .
  • Put it in synchronized Method or code block to avoid the shared resources incomplete caused by synchronous access .

2. Alternate execution

Summary of the experiment ( Whether it's done or not )

  • Two threads are executed alternately , Used wait(),notifyAll() To realize the cooperation between threads .

3. Exclusive access

3.1 modify TestUnSynchronizedThread.java Source code makes it synchronously accessible .( Screenshot of key code , Student number is required )

3.2 Further use the executor to improve the corresponding code ( Screenshot of key code , Student number is required )

Reference material :Java The multithreading Executor、ExecutorService、Executors、Callable、Future And FutureTask

4. Cooperation between threads : Producer consumer issues

4.1 function MyProducerConsumerTest.java. The result of normal operation should be that the warehouse is left 0 Goods . Run it a few more times , Observations , And answer : Is the result normal ? What's wrong ? Why? ?

  • The above two results can be obtained after running several times . Is not normal , Because there is no keyword in the code to implement communication between threads , So there is no cooperation between threads , There will be confusion .

4.2 Use synchronized, wait, notify Solve the problem ( Screenshot of key code , Student number is required )

5. Query information and answer : What is thread safety ?( Summarize with your own words and code , Write homework that you can understand )

  • If your code is in a process where multiple threads are running at the same time , These threads may run the code at the same time . If the result of each run is the same as that of single thread run , And the values of other variables are the same as expected , It's thread safe . Or say : The interface provided by a class or program is an atomic operation for a thread, or the switching between multiple threads will not cause the execution result of the interface to be ambiguous , That is to say, we don't need to think about synchronization . Thread safety problems are caused by global and static variables . If global variables in each thread 、 Static variables are read only , No write operation , Generally speaking , This global variable is thread safe ; If there are multiple threads performing write operations at the same time , In general, we need to consider thread synchronization , Otherwise, thread safety may be affected .

3. Code submission record on code cloud

Topic collection : Multithreading (4-4 To 4-10)

3.1. Code cloud code submission record

 In the project of code cloud , Choose in turn “ Statistics -Commits history - Set the time period ”, Then search and take a screenshot 



3.2 Screenshot multithreading PTA Submit list

201521123080《Java Programming 》 The first 11 Learn more articles about this week

  1. 201521123045 &lt;java Programming &gt; The first 11 Weekly learning summary

    201521123045 <java Programming > The first 11 Weekly learning summary 1. This week's learning summary 2. Written work 2. Written work Q1.1. Exclusive access and synchronous access to complete the question set 4-4( Exclusive access ) And 4-5( Synchronous access ...

  2. 201521123027 &lt;java Programming &gt; The first 11 Weekly learning summary

    1. This week's learning summary 1.1 In the way you like ( Mind mapping or something ) Summarize the related content of multithreading . 2. Written work 1. Exclusive access and synchronous access Complete the problem set 4-4( Exclusive access ) And 4-5( Synchronous access ) 1.1 Besides using synchro ...

  3. 2018 Object oriented programming (Java) The first 11 Weekly learning guidance and requirements

    2018 Object oriented programming (Java) The first 11 Weekly learning guidance and requirements (2018.11.8-2018.11.11)   Learning goals (1) master Vetor.Stack.Hashtable Use and common use of the three categories API: ...

  4. Object oriented programming (JAVA) The first 11 Weekly learning guidance and requirements

    2019 Object oriented programming (Java) The first 11 Weekly learning guidance and requirements (2019.11.8-2018.11.11)   Learning goals Understand the concept of generics : Master the definition and use of generic class : Master the declaration and use of generic methods : Master generic connection ...

  5. 20145236 《Java Programming 》 Learning summary week nine

    20145236 <Java Programming > Learning summary week nine Summary of the learning content of the textbook Chapter 16 Consolidate databases JDBC brief introduction 1.JDBC yes java Standard Specification of online database . It defines a set of standard classes and interfaces , standard API ...

  6. 2018-2019 2 20175230《Java Programming 》 Learning summary week nine

    <Java Programming > Learning summary week nine primary coverage MySQL Database management system 1. download 2. install start-up MySQL database server 1. start-up 2.root user MySQL Client management tools Establishing a connection establish ...

  7. 20175209 《Java Programming 》 Learning summary week nine

    20175209 <Java Programming > Learning summary week nine One . Summary of teaching material knowledge points There may be some problems in downloading the database, which have been found in the blog < Some problems in the process of database installation and use > The corresponding solutions are given ...

  8. 20175208 《Java Programming 》 Learning summary week nine

    20175208 2018-2019-2 <Java Programming > Learning summary week nine One . Summary of the learning content of the textbook : The first 11 Chapter JDBC And MySQL database MySQL Database management system MySQL Department of database management ...

  9. 20175202 《Java Programming 》 Learning summary week nine

    20175202 2018-2019-2 <Java Programming > Learning summary week nine Summary of teaching material knowledge points The first 11 Chapter JDBC And MySQL database MySQL Database management system MySQL Database management system , abbreviation ...

  10. 20175227 Zhang Xueying 2018-2019-2 《Java Programming 》 Learning summary week nine

    20175227 Zhang Xueying 2018-2019-2 <Java Programming > Learning summary week nine Summary of the learning content of the textbook Chapter 11 JDBC Database operation MySQL Database management system Download and install MySQL If the download is ...

Random recommendation

  1. zabbix Script alarms

    zabbix Ask the end settings : 1, Set the alarm type 2. Set user and media type send_to Namely zabbix Output $1, To whom 3. Set triggers and actions trigger test.temp_conn ( Write your own Jane ...

  2. jquery ajax use data and headers towards java RESTful Pass parameter difference

    jquery Of ajax It's a very convenient function , Make a note of $.ajax Generated http message One . Use data Pass parameters : $.ajax({ url : "webrs/test/add ...

  3. extjs In the dynamic to gridpanel Check box assignment

    Doing in recently extjs We need to dynamically give gridpanel Check box assignment of I read a lot on the Internet , No more , Finally, find a way to work as follows : RBACformPanel.getSelectionModel().sel ...

  4. HDU 5264 pog loves szh I ( character string , water )

    The question : There are two strings A and B, Will now B reverse , And then insert it into a string . Such as :A:abc   B:efg: reverse B First , change gfe: Make an insertion ,agbfce. Now give me a string , Request to restore A and B. Ideas : Sweep it over O(n), strand A stay ...

  5. bzoj 1834 [ZJOI2010]network Network expansion (MCMF)

    [ Topic link ] http://www.lydsy.com/JudgeOnline/problem.php?id=1834 [ The question ] Given a directed graph , Each side has capacity C, Expansion costs W, Ask maximum flow and increase capacity K The most ...

  6. In the workplace PPT The talent pretends to be cool 13 Tips

    Yes < persuasiveness - Let your PPT Will talk > Reader surveys show that ,88.8% Most white-collar workers think that “ Making beautiful slides is helpful for promotion ”,99.9% Most of the white-collar workers agree that the number one in the list of cool artifact in the workplace is PPT, One programmer even said that GE is the best programming ring ...

  7. Sicily 1931. Card games

    Title address :1931. Card games Ideas : It is the application of queue in data structure , You can practice your hands . The specific code is as follows : #include <iostream> #include <queue> usi ...

  8. Android In the picture processing related problems

    stay Android The development of , We often go back to deal with some picture related problems , For example, when loading pictures into memory OOM(OutOfMemory) abnormal . How much memory does the picture load into the memory .jpg png The principle and area of two common pictures ...

  9. hibernate Objects in the 3 States ---- Instantaneous state 、 Persistence state 、 Decannulated state

    Hibernate There are 3 States , Respectively : Instantaneous state (Transient).  Persistence state (Persistent). Decannulated state (Detached). Objects that are persistent are also known as PO(Persistence Object ...

  10. Use Hash Functions and MAC Generating pseudo-random numbers

    be based on Hash Functional PRNG The process is very similar to that of symmetric cryptography CTR Working mode The pseudo code of the algorithm is as follows m = ⌈n/outlen⌉ data = V W = the null String for i = 1 to m ...