多线程-MyLock实现

博客探讨了在多线程环境下计数器存在的线程问题,并通过自定义的MyLock来解决这一问题。展示了未使用MyLock时的混乱输出,以及使用MyLock后的有序输出,证明了MyLock的线程安全性。还讨论了MyLock的可重入性,并进行了相应的改进。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、计数器线程问题

import java.util.Random;

public class Sequence {

	private int value;

	public int getNext() {
		return value++;
	}

	// 测试
	public static void main(String[] args) {
		Sequence seq = new Sequence();
		// 创建多个线程
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (true) {
						System.out.println(Thread.currentThread().getName() + "===" + seq.getNext());
						try {
							Thread.sleep(50 * (new Random().nextInt(5) + 1));
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}

			}).start();
		}
	}

}

运行结果:

Thread-0===0
Thread-1===1
Thread-2===2
Thread-1===3
Thread-0===4
Thread-1===5
Thread-1===7
Thread-2===8
Thread-0===6
Thread-2===9
Thread-1===11
Thread-2===10
Thread-0===12
Thread-1===13
Thread-0===14
Thread-2===15
Thread-0===16
Thread-1===17
Thread-0===18
Thread-1===19
Thread-2===19
Thread-0===20
Thread-1===22
Thread-0===21
Thread-2===23
Thread-1===24
Thread-0===25
Thread-2===26
Thread-1===27
Thread-2===28
Thread-1===29
Thread-0===30
Thread-1===32
Thread-2===31
Thread-1===33
Thread-0===34
Thread-0===35
Thread-0===36
Thread-1===37
Thread-2===36
Thread-1===38
Thread-0===39
Thread-1===40
Thread-0===41
Thread-2===42
Thread-1===43
Thread-2===44
Thread-1===45
Thread-2===46
Thread-0===47
Thread-2===48
Thread-1===49
Thread-0===50
Thread-2===51
Thread-1===52
Thread-2===53
Thread-0===54
Thread-2===54

Thread-1===55
Thread-2===56
Thread-0===57
Thread-0===58
Thread-2===59
Thread-1===58
Thread-1===60
Thread-0===61
Thread-2===62
Thread-1===63
Thread-0===64
2、通过自己实现的锁来解决计数器的线程安全问题

计数器代码改写:

import java.util.Random;

public class Sequence {

	private int value;
	
	private MyLock lock;

	public int getNext() {
		lock.lock();
		int result = value++;
		lock.unlock();
		return result;
	}

	// 测试
	public static void main(String[] args) {
		Sequence seq = new Sequence();
		// 创建多个线程
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (true) {
						System.out.println(Thread.currentThread().getName() + "===" + seq.getNext());
						try {
							Thread.sleep(50 * (new Random().nextInt(5) + 1));
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}

			}).start();
		}
	}

}

MyLock实现:

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {
	
	private boolean isLocked = false;//获取锁的状态

	@Override
	public synchronized void lock() {
		while(isLocked)
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		isLocked = true;//第一个进来线程拿到锁,改变锁状态
	}
	
	@Override
	public synchronized void unlock() {
		if(isLocked){//当前状态为锁定状态才可释放锁
			isLocked = false;
			notify();//唤醒等待获得锁的线程
		} else {
			throw new IllegalStateException("please get lock first!");
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}

运行结果:

Thread-0===0
Thread-1===2
Thread-2===1
Thread-1===3
Thread-1===4
Thread-0===5
Thread-0===6
Thread-2===7
Thread-1===8
Thread-2===9
Thread-0===10
Thread-2===11
Thread-1===12
Thread-1===13
Thread-0===14
Thread-1===15
Thread-2===16
Thread-0===17
Thread-2===18
Thread-2===19
Thread-1===20
Thread-2===21
Thread-0===22
Thread-2===23
Thread-1===24
Thread-0===25
Thread-2===26
Thread-1===27
Thread-0===28
Thread-2===29
Thread-1===30
Thread-2===31
Thread-0===32
Thread-2===33
Thread-1===34
Thread-0===35
Thread-2===36
Thread-0===37
Thread-1===38
Thread-0===39
Thread-1===40
Thread-2===41
Thread-1===42
Thread-2===43
Thread-0===44
Thread-2===45
Thread-0===46
Thread-1===47
Thread-2===48
Thread-0===49
Thread-1===50
Thread-2===51
Thread-2===52
Thread-0===53
Thread-1===54
Thread-0===55
Thread-2===56
Thread-0===57
Thread-2===58
Thread-1===59
Thread-1===60
Thread-0===61
Thread-0===62
Thread-2===63
Thread-1===64
Thread-1===65
Thread-2===66
Thread-1===67
Thread-0===68
Thread-2===69
Thread-2===70
Thread-0===71
Thread-1===72
Thread-0===73
Thread-2===74
Thread-1===75
Thread-1===76
Thread-0===77
Thread-0===78
Thread-2===79
Thread-1===80
Thread-2===81
Thread-0===82
Thread-2===83
Thread-1===84
Thread-1===85
Thread-0===86
Thread-2===87
Thread-2===88
Thread-1===89
Thread-0===90
Thread-2===91
Thread-1===92
Thread-0===93
Thread-0===94
Thread-2===95
Thread-0===96
Thread-1===97
Thread-2===98
Thread-2===99
Thread-1===100
Thread-2===101
Thread-0===102
Thread-2===103
Thread-1===104
Thread-0===105
Thread-2===106
Thread-1===107
Thread-0===108
Thread-0===109
Thread-2===110
Thread-1===111
Thread-0===112
Thread-1===113
Thread-0===114
Thread-2===115
Thread-1===116
Thread-0===117
Thread-2===118
Thread-1===119
Thread-0===120
Thread-2===121
Thread-1===122
Thread-0===123
Thread-0===124
Thread-0===125
3、MyLock是否可重入?


public class MyLockReentrant {
	
	private MyLock lock = new MyLock();
	
	public void a(){
		lock.lock();
		System.err.println("a");
		b();
		lock.unlock();
	}
	
	public void b(){
		lock.lock();
		System.err.println("b");
		lock.unlock();
	}
	
	public static void main(String[] args) {
		MyLockReentrant lockReentrant = new MyLockReentrant();
		lockReentrant.a();
	}
}

运行结果:

线程发生无限期阻塞,说明MyLock不可重入,接下来对MyLock进行改进

4、MyLock改进为可重入

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {
	
	private boolean isLocked = false;//获取锁的状态
	
	private Thread lockThread;//当前获得锁的线程
	
	private int lockCount;//获得锁次数

	@Override
	public synchronized void lock() {
		while(isLocked && lockThread != Thread.currentThread())
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		isLocked = true;//第一个进来线程拿到锁,改变锁状态
		lockThread = Thread.currentThread();
		lockCount++;
	}
	
	@Override
	public synchronized void unlock() {
		if(isLocked){//当前状态为锁定状态才可释放锁
			if(lockThread == Thread.currentThread()){
				lockCount--;
				if(lockCount == 0){
					isLocked = false;
					notify();//唤醒等待获得锁的线程
				}
			} 
		} else {
			throw new IllegalStateException("please get lock first!");
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值