Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2339735
  • 博文数量: 2110
  • 博客积分: 18861
  • 博客等级: 上将
  • 技术积分: 24420
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-05 18:23
文章分类

全部博文(2110)

文章存档

2011年(139)

2010年(1971)

我的朋友

分类: Java

2010-10-28 12:58:41

示例代码1:

  package com.pinfo.test;

  public class ThreadTest {

  /**

  * @param args

  */

  public static void main(String[] args) {

  String lock = "lock";

  MyThread myThread = new MyThread(lock);

  Thread t1 = new Thread(myThread);

  t1.start();

  try {

  //确保线程t1先执行

  Thread.sleep(2000);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  SubThread sub = new SubThread(lock);

  Thread t2 = new Thread(sub);

  t2.start();

  }

  }

  class MyThread implements Runnable{

  String lock;

  public MyThread(String lock){

  this.lock = lock;

  }

  public void run(){

  int i = 0;

  //使用lock对象作为监视器

  synchronized(lock){

  while(i++<20){

  try {

  //每次暂停500毫秒是为了更好地看到效果

  Thread.sleep(500);

  System.out.println("The first thread.-->"+i);

  if(i==10){

  //调用lock监视器的wait()方法,通知本线程释放监视器,本线程等待

  //其他也使用lock对象作为监视器的线程唤醒的时候,本线程得以继续运行

  lock.wait();

  //下面的wait(long timeout)表示:若等待5秒后还没有别的线程来唤醒的话,则本线程继续执行

  //lock.wait(5000);

  }

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  }

  }

  }

  class SubThread implements Runnable{

  String lock;

  public SubThread(String lock){

  this.lock = lock;

  }

  public void run(){

  int i = 0;

  //这个线程也使用lock对象作为监视器

  synchronized(lock){

  while(i<10){

  i++;

  try {

  Thread.sleep(500);

  System.out.println("The second thread.-->"+i);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  //调用lock对象的notify()方法,唤醒同一对象监视器中调用wait的第一线程

  //或者调用notifyAll()方法,唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程首先被唤醒并执行

  lock.notify();

  }

  }

  }

  示例代码2:

  package com.pinfo.test;

  public class ThreadTest {

  /**

  * @param args

  */

  public static void main(String[] args) {

  MyThread myThread = new MyThread();

  //使用Runnable实现类创建线程

  Thread t1 = new Thread(myThread);

  //启动线程

  t1.start();

  try {

  //确保线程t1先执行

  Thread.sleep(2000);

  } catch (InterruptedException e1) {

  e1.printStackTrace();

  }

  int i = 0;

  //主线程使用myThread对象作为监视器

  synchronized(myThread){

  while(++i<=10){

  try {

  Thread.sleep(500);

  System.out.println("The main thread.-->"+i);

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  }

  //调用监视器的notify()方法唤醒t1线程

  myThread.notify();

  }

  }

  }

  class MyThread implements Runnable{

  public void run(){

  int i = 0;

  //使用对象本身this作为监视器(与主线程的监视器为同一个对象)

  synchronized(this){

  while(i++<20){

  try {

  Thread.sleep(500);

  System.out.println("The sub thread.-->"+i);

  if(i==10){

  //释放监视器锁,阻塞等待...

  this.wait();

  }

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  }

  }

  }

阅读(745) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~