Java---------"Threads"

Source: Internet
Author: User

在学习线程之前我们先来回顾下进程,进程就是正在运行的程序的实例,是系统分配资源的基本单位。那么线程与进程有什么关系呢?通常情况,线程是进程的一个实体,是进程的一种表现。那么我们几下来就一起学习下线程:

First, we illustrate with an example that the requirement for this instance is: by generating a random array, then sorting it and outputting the array, alternating output three times. There may be many ways to do this, but we do this in a thread-controlled way, in order to illustrate the problem, and we'll start by analyzing the following:
1. A generator with a random number is required.
2. We need to make a random array of the generated as an input. (The input output here shares an array)
3. We need to sort the input.
4. We need an output array.
5. The input and output are alternating three times. (Each time the input is initialized and then its contents are output)
Here we start coding:
Methods for generating random numbers

publicint[] initArray()    {        intarraynewint[5];        int i;        new Random();        for(i=0;i<array.length;i++)        {            array[i]=rd.nextInt(99)+1;        }        returnarray;    }

Defines an array of input and output sharing operations:

publicclass InitList {    int arry[];    boolean flag=false;//用来标示当前的线程的操作    publicintgetArry() {        return arry;    }    publicvoidsetArry(int[] arry) {        this.arry = arry;    }}

Next we initialize the input, because the thread is used to control the switching between the input and output, so we need to use a synchronous mechanism to control the input and output of the contents of the shared area of the orderly operation (one input, one output).

 Public  class initinput implements Runnable{Initlist IL; Public Initinput(Initlist IL) { This.    Il=il; }@Override     Public void Run() {//TODO auto-generated method stub        intx=0;intArray[]; Randommethod RM =NewRandommethod (); while(x<3)        {synchronized(IL) {if(Il.flag) {Try{il.wait (); }Catch(Exception e) {//}                }if(x<3) {Array=rm.initarray ();                Il.setarry (Rm.sort (array)); } il.flag=true;                Il.notify ();            x + +; }        }    }}

The careful one should find out that we have a sort of initialized input array, where the sort I use is the selection sort in brute force algorithm:

 Public int[] Selectsort (int Array[]){intI,j;intMin for(i=0;i<Array. length-1; i++) {min=i; for(j=i+1;j<Array. length;j++) {if(Array[j]<Array[min])                {min=j; }} swap (Array, min,i); }return Array; }Static voidSwapint Array[],intIintj) {intTemp temp=Array[i];Array[i]=Array[j];Array[J]=temp; }

Above we initialize the input, then we will start to implement the output section of the operation:

 Public  class initoutput implements Runnable{Initlist IL; Public Initoutput(Initlist IL) { This.    Il=il; }@Override     Public void Run() {//TODO auto-generated method stub        intArry[];intx=0; while(x<3){synchronized(IL) {if(! Il.flag) {Try{il.wait (); }Catch(Exception e) {//}} arry=il.getarry (); System.out.print (Thread.CurrentThread (). GetName () +":"); for(intI=0; i<arry.length;i++) {System.out.print ("V---:"+arry[i]);            } System.out.println (); il.flag=false;            Il.notify ();            x + +; }        }    }}

Well, everything has, only bad Main method:

publicclass Main {    publicstaticvoidmain(String args[]){        InitList IL=new InitList();        InitInput II=new InitInput(IL);        new InitOutput(IL);        new Thread(II);        new Thread(IO);        t1.start();        t2.start();    }}

This allows us to meet the requirements that can be initiated.
Now let's examine the details in more detail:
The first random number of this piece of content is relatively simple, we only need to instantiate a random, and then use his Nextint method to generate the number of randomly:
Random rd=new random ();
Rd.nextint (99) +1;//so that we can produce a number before 1-100.
The following key thread operations are here:
There are two ways to use the thread first (1. Implement runnable interface; 2. Inheriting threads), we are more commonly used is to implement runnable way. Because we can avoid the limitations of single inheritance, we can then separate it from the parent thread and encapsulate it in one object. So what is the operating mechanism of the thread? Below we can be easily understood by a graph:


On top of that, we created an instance of two threads in the main method, and then started it through start, and we used both the wait () and notify () methods in both the input and output sections, and we judged the flag value, if there is a value in the list, Then we output, releasing the execution of the current thread through wait, and then waking another thread to execute through notify (). Until the end of his life. Here we also use a keyword synchronized, this is the implementation of synchronization problem, here we involve a thread to share the same data, so it involves thread security issues, so we must implement a synchronous lock to control the operation of the shared data. As a thread-safety issue, ticketing is actually a very good case. Here I will not wordy, if there is not very clear, I can show an example to everyone, in fact, is very simple. That's about it. This part of the thread is my heart, has been afraid to touch, because of the influence of the predecessors, feeling very difficult to understand. But finally decided to study, but the harvest is not small, the sense of learning thread is also very interesting.

Java---------"Threads"

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.