------- android培训、java培训、期待与您交流! ----------
之前学习JAVA,对多线程的处理,一直使用synchronized,但看完1.5的特性之后,学会了使用LOCK替代synchroized,更灵活方便一些。
那么下面就对lock的用法用程序说明一下:
Lock_cuser类
package com.thread.lock;
import java.util.concurrent.locks.*;
/*
* 1、JDK1.5更新功能,使用LOCK替代 synchronized
* 2、优点:每一个锁可以创建多个钥匙
* */
public class Lock_cuser {
private String name;
private String sex;
private boolean flag = false;
Lock lk = new ReentrantLock();//实现Lock借口的ReentrantLock()对象
Condition cond1 =lk.newCondition();//创建一把钥匙
Condition cond2 =lk.newCondition();//又创建一把钥匙
public void set(String name, String sex){
lk.lock();
try{
while(flag)
try {
cond1.await();//cond1线程等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
this.sex = sex;
flag = true;
cond2.signalAll();//唤醒所有cond2线程
}finally{
lk.unlock();
}
}
public void put(){
lk.lock();
try{
while(!flag)
try {
cond2.await();//cond2线程等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(".....姓名:"+name+"....性别"+sex);
flag = false;
cond1.signalAll();//唤醒所有cond1线程
}finally{
lk.unlock();//释放锁
}
}
}
Lock_thread类
package com.thread.lock;
public class Lock_thread implements Runnable{
Lock_cuser i;
Lock_thread(Lock_cuser i){
this.i = i;
}
public void run(){
int t = 0;
while(true){
if(t == 0)
i.set("zhang san", "nan");
else
i.set("李四", "女");
t = (t+1)%2;
}
}
}
class Lock_thread_out implements Runnable{
Lock_cuser i;
Lock_thread_out(Lock_cuser i){
this.i = i;
}
public void run(){
while(true){
i.put();
}
}
}
主函数Lock_main类
package com.thread.lock;
public class Lock_main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Lock_cuser l = new Lock_cuser();
Lock_thread lt1 = new Lock_thread(l);
Lock_thread_out lt2 = new Lock_thread_out(l);
Thread t1 = new Thread(lt1);
Thread t2 = new Thread(lt2);
Thread t3 = new Thread(lt1);
Thread t4 = new Thread(lt2);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
-------android培训、JAVA培训、期待与您交流! ----------
--------详细请查看www.itheima.com-------------