第一种 给方法前面 加 synchronized
示例:
public synchronized void out2(String name) {
int length = name.length();
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
第二种 在方法里面加synchronized块
示例:
public void out(String name) {
int length = name.length();
synchronized (Outputer.class) {
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
第三种
java.util.concurrent.locks.Lock
给代码上锁 这个更增强大能够作到读写锁的控制
示例:
public void output(String name){
int len = name.length();
lock.lock();
try{
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}finally{
lock.unlock();
}
}
读写锁 示例:
class Queue3{
private Object data = null;//共享数据,只能有一个线程能写该数据,但能够有多个线程同时读该数据。
ReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "have read data :" + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
public void put(Object data){
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
}
}
Lock下又有一个强大的Conticion接口
Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成大相径庭的对象,以便经过将这些对象与任意 Lock 实现组合使用,为每一个对象提供多个等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
假定有一个绑定的缓冲区,它支持 put 和 take 方法。若是试图在空的缓冲区上执行 take 操做,则在某一个项变得可用以前,线程将一直阻塞;若是试图在满的缓冲区上执行 put 操做,则在有空间变得可用以前,线程将一直阻塞。咱们喜欢在单独的等待 set 中保存 put 线程和 take 线程,这样就能够在缓冲区中的项或空间变得可用时利用最佳规划,一次只通知一个线程。能够使用两个 Condition 实例来作到这一点。
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}