糊了巴图 2009-01-22 20:12
浏览 203
已采纳

初学者关于java的synchronized的弱弱的疑问

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

class TwoCounter2 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;
  public TwoCounter2(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  synchronized void run() {
    while (true) {
      t1.setText(Integer.toString(count1++));
      t2.setText(Integer.toString(count2++));
      try {
        sleep(500);
      } catch (InterruptedException e){}
    }
  }
  public synchronized void synchTest() {
    Sharing2.incrementAccess();
    
    if(count1 != count2){
      l.setText("Unsynched");
      System.out.println("count1="+count1);
     
      System.out.println("count2="+count2);
    }
  }
}

class Watcher2 extends Thread {
  private Sharing2 p;
  public Watcher2(Sharing2 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);
      } catch (InterruptedException e){}
    }
  }
}

public class Sharing2 extends Applet {
  TwoCounter2[] 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"));
        System.out.println("++"+numCounters);
      numObservers =
        Integer.parseInt(
          getParameter("observers"));
    System.out.println("++"+numCounters);
        }
    s = new TwoCounter2[numCounters];
    for(int i = 0; i < s.length; i++)
      s[i] = new TwoCounter2(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 Watcher2(Sharing2.this);
    }
  }
  public static void main(String[] args) {
    Sharing2 applet = new Sharing2();
    // This isn't an 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("Sharing2");
    aFrame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e){
          System.exit(0);
        }
      });
    aFrame.add(applet, BorderLayout.CENTER);
    aFrame.setSize(350, applet.numCounters *100);
    applet.init();
    applet.start();
    aFrame.setVisible(true);
  }
}

//以上的代码是从java思想上摘得。我搞不明白为什么,在start之后,为什么synchTest()不能返回值。
synchronized run(){}
是对run()方法加锁还是对count1和count2加锁。
问题补充:
;;;;;;;;
问题补充:
我怎么不能回答自己的帖子,我给run()是不想其他的thread访问run(),这样写是不是不可以?
问题补充:
对这也正是我不明白的地方,每个thread对象,都是调用自己的run()方法。但是加上之后和不加之后的效果完全不一样,这样就让我更糊涂了。如果在run()和synchTest()上分别上加同步限制,在run()运行之后,synchTest()的比较部分一直停留在等待状态。费解啊。
问题补充:
在run()上同步不是加给run()方法的吗?怎么是Thread锁定了thread对象呢。 那样的话我的synchTest()同样是同步了run(),为什么当start按钮按下时,synchTest()函数感觉就被挂起了呢。 我刚学,您多多点化点化。

  • 写回答

4条回答 默认 最新

  • bohemia 2009-01-22 22:05
    关注

    [quote]如果在run()和synchTest()上分别上加同步限制,在run()运行之后,synchTest()的比较部分一直停留在等待状态。费解啊。 [/quote]

    因为你对run()添加了synchronized,线程启动后,当前线程就锁定了该对象;
    你要运行synchTest();的时候,由于THread的对象已经锁定了Thread,所以你的Worker线程就要等待;

    所以,run方法,无需进行同步.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办