Java makes multiple threads

Source: Internet
Author: User
Tags class definition command line count int size sleep thread

Now consider the issue of creating multiple different threads. We can't do this with the previous example, so we have to go backwards and encapsulate run () with multiple separate classes inherited from thread. But this is a more conventional approach and easier to understand, so while the precedent reveals the coding style that we often see, it is not recommended to do so in most cases because it is slightly more complex and somewhat less flexible.
The following example reproduces the previous encoding style with counters and toggle buttons. This time, however, all the information (buttons and text fields) for a particular counter is located within its own object that inherits from thread. All fields in ticker have private (private) properties, which means that the specific implementation of the ticker can be arbitrarily modified according to the actual situation, including the number and type of data components that are used to obtain and display information. After creating a ticker object, the builder requests a handle--ticker the AWT container (Container) to populate that container with its own visual component. In this way, once the visual component is changed, the code that uses ticker does not need to be modified separately.
 

: Counter4.java//If you are separate your thread from the main/class, can have as many threads as you//want.
Import java.awt.*;
Import java.awt.event.*;

Import java.applet.*;
  Class Ticker extends Thread {private button b = New button ("Toggle");
  Private TextField t = new TextField (10);
  private int count = 0;
  Private Boolean runflag = true;
    Public Ticker (Container c) {B.addactionlistener (New Togglel ());
    panel p = new Panel ();
    P.add (t);
    P.add (b);
  C.add (P);
    Class Togglel implements ActionListener {public void actionperformed (ActionEvent e) {runflag =!runflag;
       } public void Run () {while (true) {if (Runflag) T.settext (integer.tostring (count++));
      try {sleep (100); ' Catch (Interruptedexception e) {}}} ' public class Counter4 extends Applet {private button start = new Button
  ("Start");
  Private Boolean started = false;
  Private ticker[] s; Private Boolean isapplet = TruE
  private int size; public void init () {//Get parameter ' size ' from Web page:if (isapplet) size = Integer.parseint (ge
    Tparameter ("size"));
    s = new Ticker[size];
    for (int i = 0; i < s.length i++) s[i] = new Ticker (this);
    Start.addactionlistener (New Startl ());
  Add (start);
        Class Startl implements ActionListener {public void actionperformed (ActionEvent e) {if (!started) {
        started = true;
      for (int i = 0; i < s.length i++) S[i].start ();
    }} public static void Main (string[] args) {Counter4 applet = new Counter4 ();
    This isn ' t a applet, so set the flag and//produce the parameter values from args:applet.isApplet = false;
    Applet.size = (Args.length = = 0 5:integer.parseint (args[0));
    Frame aframe = new Frame ("Counter4");
     Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {     System.exit (0);
    }
      });
    Aframe.add (applet, borderlayout.center);
    Aframe.setsize (Applet.size * 50);
    Applet.init ();
    Applet.start ();
  Aframe.setvisible (TRUE); }
} ///:~


Ticker not only includes its own threading mechanism, but also provides tools for controlling and displaying threads. You can create as many threads as you want without explicitly creating a windowing component.
In Counter4, there is an array of ticker objects named S. For maximum flexibility, the length of this array is initialized by touching the Web page with the program's parameters. The following are the approximate length parameters in a Web page, which are embedded in the description of the program piece (applet):
<applet code=counter4 width=600 height=600>
<param name=size value= ">"
</applet>
where param,name and value are keywords that apply to all Web pages. Name refers to a reference to a parameter in a program, and value can be any string (not just something that is parsed into a number).
We note that the judgment of the length of the array s is done inside Init () and it is not provided as part of the inline definition of S. In other words, the following code cannot be used as part of a class definition (should be outside of any method):
Inst size = Integer.parseint (getparameter ("size"));
Ticker[] s = new Ticker[size]
It can be compiled, but it will get a null pointer violation at run time. However, if you initialize GetParameter () to Init (), it works. The patch framework makes the necessary startup work to gather some parameters before entering Init ().
In addition, the above code is simultaneously set up as a piece of program and an application (program). In the case where it is an application, the size parameter can be extracted from the command line (otherwise a default value is provided).
After the length of the array is built, you can create a new ticker object, and as part of the ticker builder, the button and text fields for each ticker are added to the program.
When the Start button is pressed, the entire ticker array is traversed and the start () is invoked for each ticker. Remember that start () makes the necessary thread initialization work, and then calls run () for that thread.
The Togglel Monitor simply toggles the tag in the ticker, and once the corresponding thread needs to modify the tag, it responds accordingly.
One advantage of this example is that it allows us to easily create large collections of individual subtasks and to monitor their behavior. In this case, we will find that as the number of subtasks increases, the number of machines displayed may be more divided, due to the way the threads are serviced.
Also try to experience the important role of sleep (100) in Ticker.run (). If you remove sleep (), the situation still progresses well before you press a toggle button. When the button is pressed, the particular thread will have a failed runflag, and run () will fall deeply into an infinite loop-it is difficult to abort the exit during the multitasking process. Therefore, the response sensitivity of the program to the user operation will be greatly reduced.

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.