java多线程之间通讯

1 实现一个线程+1 一个线程 -1

class Share511 {
	public int a = 0;
}
class Thread552 implements Runnable{
	Share511 share;
	@Override
	public void run() {
		while(true){
			synchronized (share) {
				int a = share.a;
				if(a == 0){
					share.a =a+1;
					System.out.println("a+1 " + share.a);
					share.notify();
				}else{
					try {
						share.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}	
		}
	}
	public Thread552(Share511 share) {
		this.share = share;
	}
}
class Thread553 implements Runnable{
	Share511 share;
	@Override
	public void run() {
		while(true){
			synchronized (share) {
				int a = share.a;
				if(a == 1){
					share.a = a - 1;
					System.out.println("a-1 " + share.a);
					share.notify();
				}else{
					try {
						share.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public Thread553(Share511 share) {
		this.share = share;
	} 	
}
public class Thread5 {
	public static void main(String[] args) {
		Share511 share511 = new Share511();
		Thread thread552 = new Thread(new Thread552(share511));
		thread552.start();
		Thread thread553 = new Thread(new Thread553(share511));
		thread553.start();
	}
}

2 sleep()与wait()区别

  1. sleep()属于方法是属于Thread类中的方法
  2. sleep()不会释放对象锁wait()对象锁

3 Lock写法:

Lock lock  = new ReentrantLock();
lock.lock();
try{
//可能会出现线程安全的操作
}finally{
//一定在finally中释放锁
//也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
  lock.ublock();
}

4 Condition用法

Condition condition = lock.newCondition();
condition.await();  类似wait
Condition.signal() 类似notify

5 守护线程
Java中有两种线程一种是用户线程,另一种是守护线程
当进程不存在或主线程停止守护线程也会被停止
使用setDaemon(true)方法设置为守护线程

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值