线程 :循环打印A,B 方法一:利用wait notify

1.获取对象锁

2.使用   wait和notify执行(通过对象锁),唤醒其他线程  ,关闭当前线程

3.循环操作2个线程


实例:

package com.wu.threadDemo;
public class PrintDemo {
 public static void main(String[] args) {
//2个对象锁
  Object A = new Object();
  Object B = new Object();

//线程传参:打印出不同内容,对象锁也改变
  PrintDemo p = new PrintDemo();
  print a = p.new print(A,B,"A");
  print b = p.new print(B,A,"B");

  Thread a1 = new Thread(a);
  Thread a2 = new Thread(b);

  a1.start();
  a2.start();
  
 }
 
 class print implements Runnable{
  Object self;
  Object next;
  String str;
  
  public String getStr() {
   return str;
  }

  public print(Object self, Object next, String str) {
   super();
   this.self = self;
   this.next = next;
   this.str = str;
  }

  public void run() {
   while(true)
   {
   synchronized (self) {
    synchronized (next) {
     System.out.println(this.getStr());
      next.notify();
    }
    try {
      self.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    
   }
   }
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值