Java thread (1): thread security and insecurity

Source: Internet
Author: User

As a Java Web Developer, there is very little need to process threads, because the server has already helped us deal with them. I remember that when I first learned Java, the teacher took us into a LAN chat room and used AWT, socket, multithreading, I/O, and the client and server, at that time, I was very excited. I went back to school to give a demonstration to my students. I felt like I was a good Nb. The last time I saw a prompt at the Baidu Developer Conference, I wrote my own code. I did not read other people's code for six months, and I learned the same thing, if the learned knowledge is not used or often reviewed, it is not your own knowledge. I believe that many people share the same Java skills that have been used for less than four years in the university. If the javase foundation is not fixed, I am eager to engage in javaee, then I learned about front-end development (HTML, CSS, and JavaScript), maybe jquery and extjs, then struts, hibernate, and spring. Then I heard that I had to find a job in Linux and Oracle, I went to study again. In this process, I was lost. Although I learned a wide range of topics, I think that the yellow pharmacists in "The Condor Heroes" commented on Yang Guo, but they were not refined, mixed, and unpure, with this string, I feel that it is difficult to develop Java. It is not difficult to learn, but a wide range of knowledge. I have to be proficient in it, and I want to be proficient in it. This is just my idea when I am confused, now I have found the direction.

Back to the question, when we look at the jdk api, we will always find some class instructions that indicate thread safety or thread safety. For example, in stringbuilder, there is such a sentence:StringBuilderIt is not safe to use instances for multiple threads. If such synchronization is required, we recommend that you useStringBuffer. ", Then manually create a thread unsafe class, and then use this class in multiple threads to see what the effect is.

Count. Java:

public class Count {private int num;public void count() {for(int i = 1; i <= 10; i++) {num += i;}System.out.println(Thread.currentThread().getName() + "-" + num);}}

In this class, the count method calculates the sum of the current thread name and sum that 1 has been added to 10, and we expect that each thread will output 55.

Threadtest. Java:

public class ThreadTest {public static void main(String[] args) {Runnable runnable = new Runnable() {Count count = new Count();public void run() {count.count();}};for(int i = 0; i < 10; i++) {new Thread(runnable).start();}}}

10 threads are started here. Let's take a look at the output:

Thread-0-55Thread-1-110Thread-2-165Thread-4-220Thread-5-275Thread-6-330Thread-3-385Thread-7-440Thread-8-495Thread-9-550

Only the results output by the thread-0 thread are what we expect, and the output is accumulated every time. The reason for this accumulation will be explained in the blog post, so we need to get the expected results, there are several solutions:

1. Convert num in count to the local variable of the count method;

public class Count {public void count() {int num = 0;for(int i = 1; i <= 10; i++) {num += i;}System.out.println(Thread.currentThread().getName() + "-" + num);}}

2. Get the Thread class member variable to the run method;

public class ThreadTest4 {public static void main(String[] args) {Runnable runnable = new Runnable() {public void run() {Count count = new Count();count.count();}};for(int i = 0; i < 10; i++) {new Thread(runnable).start();}}} 

3. Different thread classes are used to start a thread each time. It is not recommended.
In the above test, we found that the class with member variables is insecure when used in multiple threads, and the variables are defined as thread-safe in the method. When using struts1, it is not recommended to create member variables because action is a singleton. If a member variable is created, thread security risks may occur, struts2 creates an action for each request, so you do not need to consider thread security issues.

Next article: Java thread (2)

This article is from: Gao Shuang | coder, original address: http://blog.csdn.net/ghsau/article/details/7421217.

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.