(One interview question) thread and thread

Source: Internet
Author: User

(One interview question) thread and thread

I. Main advantages of multithreading: improved efficiency. But thread security exists. The Code is as follows:

Realistic multi-Thread method: implements the Runnable interface and inherits the Thread class

(Generally, the Runnable interface is implemented mainly because java does not support multiple inheritance. Once you inherit the Thread class, you cannot inherit other classes and the limitations are too large)

I. multi-thread implementation

1. Here I implement the Runnable interface to implement Multithreading

Public class Producter implements Runnable {public static List <String> nlist = new partition List <String> (); // stores the product private Integer number; // stores the product number private String productName; // store the product name/** implement the Runnable interface to produce the product and add it to the container * // @ Overridepublic void run () {// define the product number, number = nlist. size () + 1; // define the product name productName = number + "No. Product"; // store the product in the container nlist. add (productName); // TODO Auto-generated method stub }}

2. Test class, defining 100 threads to test multithreading Problems

Public class TestDemo {public static void main (String [] args) throws InterruptedException {// produce 100 products for (int I = 0; I <100; I ++) {Thread thread = new Thread (new Producter (); thread. start ();} // wait for 3 s because the main thread and thread are in parallel. the value of nlist not waiting for return is unknown. thread. sleep (3000); // traverses the product (String s: Producter. nlist) {System. out. println (s );}}}

3. Experiment results:

4. analysis results:

This is because multiple threads simultaneously access the run () method, causing a product to be manufactured multiple times.

Ii. multi-thread security solution: Lock (synchronized keyword)

Lock the run () method. ---- purpose: only allow up to one thread to access the run () method when the object accesses run (). This solves the problem that a product is created multiple times.

1. Modify the Producter Method

Public class Producter implements Runnable {public static List <String> nlist = new partition List <String> (); // stores the product private Integer number; // stores the product number private String productName; // store the product name/** implement the Runnable interface to produce the product and add it to the container */@ Overridepublic void run () {// The lock allows a maximum of one thread to come in synchronized (this. getClass () {// define the product number, starting from 1. number = nlist. size () + 1; // define the product name productName = number + "No. Product"; // store the product in the container nlist. add (productName); // TODO Auto-generated method stub }}}

2. modified the test class code for easy viewing (10 lines per print ):

Public class TestDemo {private static int count = 0; public static void main (String [] args) throws InterruptedException {// produces 100 products for (int I = 0; I <100; I ++) {Thread thread = new Thread (new Producter (); thread. start ();} // wait for 3 s because the main thread and thread are in parallel. the value of nlist not waiting for return is unknown. thread. sleep (3000); // traverses the product (String s: Producter. nlist) {// newline count ++ every 10 times; System. out. print (s); if (count % 10 = 0) {System. out. println ();}}}}

3. Experiment results (no duplicate ):

 

4. Summary

Thread security issues must be taken into account when implementing multithreading, otherwise there will be many unexpected results (bugs )~

Related Article

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.