练手java thread(五)

本文介绍如何利用Lock对象的lock()和unlock()方法来确保线程安全,并通过具体示例MyStack展示其实现过程。此外,还介绍了读写锁(ReadWriteLock)的概念及其在并发控制中的应用。
摘要由CSDN通过智能技术生成

通过Lock对象的lock()和unlock()方法来模拟synchronized待模块。

 

1.Lock lock = new ReentrantLock();

2.ReadWriterLock rwl = new ReentrantReadWriterLock();是用来维护读取与写入分离的lock,同时可以有多个线程持有readlock,因为read通常是安全的并发操作;但只有一个线程可以持有write lock。

(if a thread has a write lock,nobody can have read/write lock.)

 

入口类:

package thread.test05;

public class LockTest {
	public static void main(String[] args) {
		MyStack stack=new MyStack(20);
		Thread t1=new MyThreadA(stack);
		Thread t2=new MyThreadB(stack);
		t1.start();
		t2.start();
		
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(stack);

	}
}

class MyThreadA extends Thread{
	private MyStack stack;
	
	public MyThreadA (MyStack stack){
		this.stack=stack;
	}
	
	public void run(){
		for(int i=0;i<10;i++){
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stack.push(i+"");
		}
	}
}

class MyThreadB extends Thread{
	private MyStack stack;
	
	public MyThreadB (MyStack stack){
		this.stack=stack;
	}
	
	public void run(){
		for(int i=0;i<10;i++){
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stack.push((char)('A'+i)+"");
		}
	}
}


 MyStack类如下:

package thread.test05;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyStack {
	private Object[] data;
	private int count;
	private Lock lock;
	
	public MyStack(int size){
		data=new Object[size];
		count=0;
		lock=new ReentrantLock();
	}
	
	public void push(Object obj){
		lock.lock();
		try{
			if(count==data.length){
				throw new FullStackException("栈空间已满!");
			}
			data[count]=obj;
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			count++;
		}
		finally{
			lock.unlock();
		}

	}
	
	public String toString(){
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<count;i++){
			sb.append(data[i]+",");
		}
		return sb.toString();
	}

}

经测试,MyStack中的数据不会发生混乱。

 //

读写锁:

 

package thread.test05;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockTest2 {
	private final ReadWriteLock rwl = new ReentrantReadWriteLock();
	private final Lock r = rwl.readLock();
	private final Lock w = rwl.writeLock();
	
	
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值