Error methods for Java resource access

Source: Internet
Author: User

Now consider a different way to use the counters that are frequently seen in this chapter. In the following example, each thread contains two counters that add value and display in the run (). In addition, we used another thread of the Watcher class. Its role is to monitor the counters to see if they remain equal. This surface is a meaningless action, because if you look at the code, you'll find that the counter is definitely the same. But the reality is not necessarily the case. The following is the first version of the program:
 

: Sharing1.java//Problems with resource sharing while threading import java.awt.*;
Import java.awt.event.*;

Import java.applet.*;
  Class Twocounter extends Thread {Private Boolean started = false;
  Private TextField T1 = new TextField (5), t2 = new TextField (5);
  Private label L = new label ("Count1 = = Count2");
  private int count1 = 0, count2 = 0;  ADD the display components as a panel//to the given Container:public Twocounter (container c) {panel p = new
    Panel ();
    P.add (t1);
    P.add (T2);
    P.add (l);
  C.add (P);
      public void Start () {if (!started) {started = true;
    Super.start ();
      } public void Run () {while (true) {T1.settext (integer.tostring (count1++));
      T2.settext (integer.tostring (count2++));
      try {sleep (500);
    The catch (Interruptedexception e) {}}} is public void Synchtest () {sharing1.incrementaccess ();
  if (count1!= count2) l.settext ("unsynched"); }
Class Watcher extends Thread {private Sharing1 p;
    Public Watcher (Sharing1 p) {this.p = P;
  Start ();
      public void Run () {while (true) {for (int i = 0; i < p.s.length i++) p.s[i].synchtest ();
      try {sleep (500);
  The catch (Interruptedexception e) {}}} is public class Sharing1 extends Applet {twocounter[] s;
  private static int accesscount = 0;
  private static TextField acount = new TextField ("0", 10);
    public static void Incrementaccess () {accesscount++;
  Acount.settext (integer.tostring (Accesscount));
  Private Button start = New button ("Start"), observer = New button ("observe");
  Private Boolean isapplet = true;
  private int numcounters = 0;
  private int numobservers = 0;
      public void init () {if (isapplet) {numcounters = Integer.parseint (getparameter ("size"));
    Numobservers = Integer.parseint (GetParameter ("observers")); } s = new TwOcounter[numcounters];
    for (int i = 0; i < s.length i++) s[i] = new Twocounter (this);
    panel p = new Panel ();
    Start.addactionlistener (New Startl ());
    P.add (start);
    Observer.addactionlistener (New Observerl ());
    P.ADD (Observer);
    P.add (New Label ("Access Count");
    P.add (acount);
  Add (P); Class Startl implements ActionListener {public void actionperformed (ActionEvent e) {for (int i = 0; i < S.length;
    i++) S[i].start (); } class Observerl implements ActionListener {public void actionperformed (ActionEvent e) {for (int i = 0; i < numobservers;
    i++) New Watcher (Sharing1.this);
    } public static void Main (string[] args) {Sharing1 applet = new Sharing1 ();
    This isn ' t a applet, so set the flag and//produce the parameter values from args:applet.isApplet = false;
    Applet.numcounters = (Args.length = = 0 5:integer.parseint (args[0)); Applet.numobsErvers = (Args.length < 2 5:integer.parseint (args[1));
    Frame aframe = new Frame ("Sharing1"); Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {SYSTEM.E
        XIT (0);
    }
      });
    Aframe.add (applet, borderlayout.center);
    Aframe.setsize (Applet.numcounters, *100);
    Applet.init ();
    Applet.start ();
  Aframe.setvisible (TRUE); }
} ///:~


As always, each counter contains its own display component: Two text fields and a label. Depending on their initial values, you know that the count is the same. These components join the container in the Twocounter builder. Start () may be invoked more than once because this thread is started by a user's "press button" operation. But for a thread to say, multiple calls to Thread.Start () are illegal (and will result in an offence). In the started tag and overload start () method, you can see the precautions taken to address this situation.
In Run (), the increment and display of count1 and Count2 seem to keep them exactly the same. The sleep () is then invoked, and if there is no such call, the program will make an error because it makes it difficult for the CPU to swap tasks.
The Synchtest () method takes the seemingly meaningless action of checking whether Count1 equals Count2, and if not, set the label to "unsynched" (not synchronized). But first, it calls a static member of the class Sharing1 to add value and display an access counter, indicating how many times this check has been successfully performed (the rationale for this will become apparent in other versions of this example).
The Watcher class is a thread that is called synchtest () for all Twocounter objects that are active. In the meantime, it iterates through the arrays that are accommodated in the Sharing1 object. Watcher can be imagined as it flitted over the shoulders of Twocounter objects constantly "peeking".
The Sharing1 contains an array of Twocounter objects initialized by Init () and started as a thread after we pressed the "Start" button. If you press the "observe" button later, you will create one or more observers and investigate the unprotected twocounter.
Note In order for it to run as a piece of program in a browser, the Web page needs to include the following lines:

Code=sharing1 width=650 height=500> <param name=size value=
"<applet" >
<param name= Observers value= "1" >
</applet>


Can change the width, height and parameters, according to their own will test. If you change the size and observers, the behavior of the program changes. We also note that by accepting parameters from the command line (or by using the default values), it is designed to run as a stand-alone application.
The following are the most "incredible". In Twocounter.run (), an infinite loop simply repeats adjacent rows repeatedly:
T1.settext (integer.tostring (count1++));
T2.settext (integer.tostring (count2++));
(As with "sleep", but it's not important here). However, when the program is running, you will find that Count1 and Count2 are "observed" (observed by watcher) are not equal in number of times! This is caused by the nature of the threads-they can hang at any time (pause). As a result, there are occasional execution pauses between the execution times of the above two lines. At the same time, the watcher thread is also just following in, and is exactly at this time to compare, causing the counter to appear unequal.
This example reveals a very basic problem when using threads. We have no way of knowing when a thread is going to run. Imagine sitting in front of a table with a fork on the table, ready to fork your last piece of food. When the fork touches the food, the food suddenly disappears (because the thread is suspended and another thread comes in and steals the food). This is the problem that we have to solve.
Sometimes, we don't mind if a resource is being accessed while trying to use it (food is on another plate). But in order for multithreaded mechanisms to function properly, some measures are needed to prevent two of threads from accessing the same resources-at least at a critical time.
To prevent such conflicts, simply lock the thread when it is using a resource. After the first thread that accesses the resource is locked, the other thread can no longer use that resource unless it is unlocked. If the front seat of the car is a limited resource, shout "This is mine!" "The child would argue to lock it up.

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.