Write before:
The topics of this article are all made up by myself. The teacher did not give the topic selection of this experimental report. He asked us to give free play and create our own background. We should include the knowledge points of thread design, thread mutual exclusion and synchronization. Therefore, I made up two topics by myself. I didn't look carefully. There may be some problems. If you find any problems, please help correct them! The first question reflects thread mutual exclusion, the second question reflects thread synchronization, and both questions reflect how to design threads. This paper gives my title, implementation code and operation results. For this experimental report, this paper is only for reference, and the specific work has to be completed according to the background created by you.
All right, stop talking nonsense and go to the topic.
1. Xiao Wang, Xiao Li and Xiao Chen should all use the office printer to print, and all three should print ten copies of materials. The office has only one printer for printing. In short, the three people have three printing threads. The three printing threads compete for one printer resource, forming thread mutual exclusion. In order to enable the three people to complete their respective printing tasks without problems, write a program using the relevant method to deal with the thread mutual exclusion problem. Among them, we need to define the printer Printer class, including the count used to print the total number of printing materials, and the method used for printing print. We need to define the material of the Thread class to print the class MaterialPrint, rewrite the run () method, and call the print method. Create a three person material printing thread in the test class and start it. Finally, the solution of thread mutual exclusion is required.
Here is a description of thread mutex:
When multiple threads need to access the same resource, only one thread is allowed to operate the shared resource in a time period. After the operation, other threads can read the resource. This is called thread mutual exclusion. We need to use synchronized to lock the shared area to ensure the security of shared resources.
Implementation code:
package com.zhangyufan.thread; public class TestPrinter { public static void main(String[] args) { Printer p = new Printer(); MaterialPrint mp1 = new MaterialPrint("Xiao Wang", p); MaterialPrint mp2 = new MaterialPrint("petty thief", p); MaterialPrint mp3 = new MaterialPrint("Xiao Chen", p); mp1.start(); mp2.start(); mp3.start(); try { mp1.join(); mp2.join(); mp3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("After printing, the total number of printed materials is:" + p.count); } } class Printer { public int count = 0; public synchronized void print() { for (int i = 1; i <= 10; i++) { System.out.println("Executing" + Thread.currentThread().getName() + "The first" + i + "The total number of printed materials is:" + (count++)); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } } class MaterialPrint extends Thread { private Printer p = null; public MaterialPrint(String name, Printer p) { super(name); this.p = p; } @Override public void run() { p.print(); } }
Operation results:
We can find that when there is only one printer, the print threads of three people start at the same time. Whoever grabs the print thread first will complete the print task first. After completing the print task of a certain person, we will wait for the next grabbing print thread and complete the corresponding print task. In this way, there will be no printing disorder and other problems, and the mutual exclusion of threads is realized.
2. Select two mobile phones, one is apple mobile Phone using ios system and the other is Huawei mobile Phone using Hongmeng system. In the apple mobile Phone store and Huawei mobile Phone store in a shopping mall, consumers have been buying Apple mobile phones and Huawei mobile phones. According to the recent business conditions of the two mobile Phone stores, consumers will always come to buy, which means that they always need to produce these two mobile phones. There is no conflict between consumers' purchase behavior and manufacturers' production of these two mobile phones. Thread synchronization is formed in the process of production and consumption, and data needs to be shared. Use relevant methods to write a program to deal with the thread synchronization problem. It contains the mobile Phone class, which defines the name and system used, represents a mobile Phone, and provides the operations of production () and getProduct () for producing and purchasing mobile phones. It is necessary to define the producer class producer, implement the Runnable interface, rewrite the run () method and call the operation of the production mobile Phone. It is necessary to define the Consumer class Consumer, implement the Runnable interface, rewrite the run () method and call the operation of purchasing the mobile Phone. In the test class, create a mobile Phone object as a shared data area, create a producer object and a Consumer object, create two threads and start.
Here is a description of thread synchronization:
In some cases, threads need to execute alternately. For example, a thread stores data to a storage unit, while another operation performs a value taking operation. These threads need to be synchronized to complete the access task. To solve the problem of alternating thread execution but ensuring the safety of shared resources, you need to use three Java methods: wait(), notify() and notifyAll(). These three methods are member methods of the Object class, so you can use these three methods in any class.
Implementation code:
package com.zhangyufan.thread; public class TestProductorConsumer { public static void main(String[] args) throws InterruptedException { Phone p = new Phone(); Productor pro = new Productor(p); Consumer con = new Consumer(p); new Thread(pro).start(); new Thread(con).start(); Thread.sleep(20000); System.out.println("The producers produced a total of" + (p.i + p.j) + "Mobile phone"); System.out.println("Consumers bought a total of" + (p.i + p.j) + "Mobile phone"); } } class Phone { private String name = "iPhone"; private String system = "ios system"; private boolean flag = true; public int i = 0; public int j = 0; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSystem() { return system; } public void setSystem(String system) { this.system = system; } public synchronized void production(String name, String system) { if (!flag) { try { super.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.setName(name); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } this.setSystem(system); if (this.getName().equals("iPhone")) { System.out .println("Produced one" + this.getName() + "---" + this.getSystem() + "---Mobile number:" + this.getName() + (++i)); } else { System.out .println("Produced one" + this.getName() + "---" + this.getSystem() + "---Mobile number:" + this.getName() + (++j)); } flag = false; super.notify(); } public synchronized void getProduct() { if (flag) { try { super.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("The consumer bought one" + this.getName()); flag = true; super.notify(); } } class Productor implements Runnable { private Phone p = null; public Productor(Phone p) { this.p = p; } @Override public void run() { for (int i = 0; i < 30; i++) { if (i % 2 != 0) { this.p.production("iPhone", "ios system"); } else { this.p.production("Huawei mobile phone", "Hongmeng system"); } } } } class Consumer implements Runnable { private Phone p = null; public Consumer(Phone p) { this.p = p; } @Override public void run() { for (int i = 0; i < 30; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } this.p.getProduct(); } } }
Operation results:
We can find that there is no conflict between manufacturers' production of mobile phones and consumers' purchase of mobile phones. The process of producing mobile phones and purchasing mobile phones reflects thread synchronization, and finally realizes the problem requirements.