浅谈Java多线程的同步问题

发表于:2010-4-22 10:45  作者:未知   来源:51Testing软件测试网采编

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签:

  代码

package com.vista;
class MyThread implements java.lang.Runnable {
private int threadId;
private static Object lock = new Object();
  public MyThread(int id) {
  this.threadId = id;
  }

  @Override
  public void run() {
    synchronized (lock) {
      for (int i = 0; i < 100; ++i) {
      System.out.println("Thread ID: " + this.threadId + " : " + i);
      }
    }
  }
}

public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
  public static void main(String[] args) throws InterruptedException {
    for (int i = 0; i < 10; ++i) {
      new Thread(new MyThread(i)).start();
      Thread.sleep(1);
    }
  }
}

  再来看第一段代码,实例方法中加入sychronized关键字封锁的是this对象本身,而在静态方法中加入sychronized关键字封锁的就是类本身。静态方法是所有类实例对象所共享的,因此线程对象在访问此静态方法时是互斥访问的,从而可以实现线程的同步,代码如下所示:

  代码

package com.vista;
class MyThread implements java.lang.Runnable {
private int threadId;
  public MyThread(int id) {
  this.threadId = id;
  }
  
  @Override
  public void run() {
  taskHandler(this.threadId);
  }
  private static synchronized void taskHandler(int threadId) {
    for (int i = 0; i < 100; ++i) {
    System.out.println("Thread ID: " + threadId + " : " + i);
    }
  }
}

public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
  public static void main(String[] args) throws InterruptedException {
    for (int i = 0; i < 10; ++i) {
      new Thread(new MyThread(i)).start();
      Thread.sleep(1);
    }
  }
}


22/2<12

评 论

论坛新帖



建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2022, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道