synchronized(list){ //获得锁
list.append();
list.count();
}//释放锁
package com.kang;
import java.util.LinkedList;
import java.util.List;
public class Demo1 {
public static void main(String[] args){
List list = new LinkedList();
Thread r = new Thread(new ReadList(list));
Thread w = new Thread(new WriteList(list));
r.start();//1.读线程先执行
w.start();//2、写线程后执行
}
}
class ReadList implements Runnable{
private List list;
public ReadList(List list){ this.list = list; }
@Override
public void run(){
System.out.println("ReadList begin at "+System.currentTimeMillis());
synchronized (list){//3、读线程获得线程锁
try {
Thread.sleep(1000);
System.out.println("list.wait() begin at "+System.currentTimeMillis());
list.wait();//4、读线程立即释放了线程锁,等待其他线程的notify操作
System.out.println("list.wait() end at "+System.currentTimeMillis());
//9、读线程获得线程执行权
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ReadList end at "+System.currentTimeMillis());
}
}
class WriteList implements Runnable{
private List list;
public WriteList(List list){ this.list = list; }
@Override
public void run(){
System.out.println("WriteList begin at "+System.currentTimeMillis());
synchronized (list){//5、写线程获得了线程锁
System.out.println("get lock at "+System.currentTimeMillis());
list.notify();//6、唤醒其他线程并且在写线程在执行完线程块后立即释放线程锁
System.out.println("list.notify() at "+System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("get out of block at "+System.currentTimeMillis());
}//7、同步块执行完毕
System.out.println("WriteList end at "+System.currentTimeMillis());
//8、写线程获得抢到线程执行权
}
}
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
package com.kang;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Demo2 {
public static void main(String[] args) {
List list = new LinkedList();
for (int i = 0; i < 10000; i++) {
list.add(i);
}
final RWLockList rwLockList = new RWLockList(list);// 初始化数据
Thread writer = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
rwLockList.put(i);
}
}
});
Thread reader1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
rwLockList.get(i);
}
}
});
Thread reader2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
rwLockList.get(i);
}
}
});
long begin = System.currentTimeMillis();
writer.start();
reader1.start();
reader2.start();
try {
writer.join();
reader1.join();
reader2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("RWLockList take "
+ (System.currentTimeMillis() - begin) + "ms");
}
}
class RWLockList {// 读写锁
private List list;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public RWLockList(List list) {
this.list = list;
}
public int get(int k) {
readLock.lock();
try {
return (int) list.get(k);
} finally {
readLock.unlock();
}
}
public void put(int value) {
writeLock.lock();
try {
list.add(value);
} finally {
writeLock.unlock();
}
}
}
package com.kang;
import java.util.LinkedList;
import java.util.List;
public class Demo3 {
public static void main(String[] args) {
List list = new LinkedList();
for (int i = 0; i < 10000; i++) {
list.add(i);
}
final SyncList syncList = new SyncList(list);// 初始化数据
Thread writerS = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
syncList.put(i);
}
}
});
Thread reader1S = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
syncList.get(i);
}
}
});
Thread reader2S = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
syncList.get(i);
}
}
});
long begin1 = System.currentTimeMillis();
writerS.start();
reader1S.start();
reader2S.start();
try {
writerS.join();
reader1S.join();
reader2S.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("SyncList take "
+ (System.currentTimeMillis() - begin1) + "ms");
}
}
class SyncList {
private List list;
public SyncList(List list) {
this.list = list;
}
public synchronized int get(int k) {
return (int) list.get(k);
}
public synchronized void put(int value) {
list.add(value);
}
}
package com.kang;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class InterruptedLock extends Thread {
private static Lock lock = new ReentrantLock();
@Override
public void run() {
try {
// 可中断的尝试获取锁,如果在尝试获取锁的过程中当前线程被中断(thread.interrupt()), 将抛出InterruptedException异常
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("interruption happened");
return;
}
// 如果运行到这里, 说明已经申请到锁, 且没有发生异常
try {
System.out.println("run is holding the lock");
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
try {
lock.lock();
System.out.println("main is holding the lock.");
Thread thread = new InterruptedLock();
thread.start();
Thread.sleep(1000);//该线程此时应该阻塞在lockInterruptibly方法上
thread.interrupt();// 中断thread线程,导致其抛出InterruptedException异常.
Thread.sleep(1000);
} finally {
lock.unlock();
}
}
}
public boolean transferMoney(Account fromAcct, Account toAcct, DollarAmount amount, long timeout, TimeUnit unit)
throws InsufficientFundsException, InterruptedException {
long fixedDelay = getFixedDelayComponentNanos(timeout, unit);
long randMod = getRandomDelayModulusNanos(timeout, unit);
// 截止时间
long stopTime = System.nanoTime() + unit.toNanos(timeout);
while (true) {
if (fromAcct.lock.tryLock()) {
try {
if (toAcct.lock.tryLock()) {
try {
if (fromAcct.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else {
fromAcct.debit(amount);
toAcct.credit(amount);
return true;
}
} finally {
// 成功申请到锁时才需要释放锁
toAcct.lock.unlock();
}
}
} finally {
// 成功申请到锁时才需要释放锁
fromAcct.lock.unlock();
}
}
// 如果已经超过截止时间直接返回false, 说明转账没有成功. 否则进行下次尝试.
if (System.nanoTime() < stopTime)
return false;
NANOSECONDS.sleep(fixedDelay + rnd.nextLong() % randMod);
}
}
五、一道多线程的解答
1、题目
启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:
线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5
线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10
...
线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75
2、使用内置锁实现
package com.kang;
public class NumberPrintDemo {
// n为即将打印的数字,是逐渐递增的。
private static int n = 1;
// state=1表示将由线程1打印数字, state=2表示将由线程2打印数字, state=3表示将由线程3打印数字
private static int state = 1;
public static void main(String[] args) {
final NumberPrintDemo pn = new NumberPrintDemo();
new Thread(new Runnable() {
public void run() {
// 3个线程打印75个数字, 单个线程每次打印5个连续数字, 因此每个线程只需执行5次打印任务. 3*5*5=75
for (int i = 0; i < 5; i++) {
// 3个线程都使用pn对象做锁, 以保证每个交替期间只有一个线程在打印
synchronized (pn) {
// 如果state!=1, 说明此时尚未轮到线程1打印, 线程1将调用pn的wait()方法, 直到下次被唤醒,以此保证三个线程的执行顺序
while (state != 1)//注意这里不能使用if
try {
pn.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 当state=1时, 轮到线程1打印5次数字
for (int j = 0; j < 5; j++) {
// 打印一次后n自增
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
// 线程1打印完成后, 将state赋值为2, 表示接下来将轮到线程2打印,从而指定了线程的执行顺序
state = 2;
// notifyAll()方法唤醒在pn上wait的线程2和线程3, 同时线程1将退出同步代码块, 释放pn锁.
// 因此3个线程将再次竞争pn锁
// 假如线程1或线程3竞争到资源, 由于state不为1或3, 线程1或线程3将很快再次wait, 释放出刚到手的pn锁.
// 只有线程2可以通过state判定, 所以线程2一定是执行下次打印任务的线程.
pn.notifyAll();
}
}
}
}, "线程1").start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (pn) {
while (state != 2)
try {
pn.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
state = 3;
pn.notifyAll();
}
}
}
}, "线程2").start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (pn) {
while (state != 3)
try {
pn.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
state = 1;
pn.notifyAll();
}
}
}
}, "线程3").start();
}
}
package com.kang;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class NumberPrint implements Runnable {
private int state = 1;
private int n = 1;
// 使用lock做锁
private ReentrantLock lock = new ReentrantLock();
// 获得lock锁的3个分支条件
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
@Override
public void run() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
// 线程1获得lock锁后, 其他线程将无法进入需要lock锁的代码块.
// 在lock.lock()和lock.unlock()之间的代码相当于使用了synchronized(lock){}
lock.lock();
while (state != 1)
try {
// 线程1竞争到了lock, 但是发现state不为1, 说明此时还未轮到线程1打印.
// 因此线程1将在c1上wait
// 与内置锁不同的是, 三个线程并非在同一个对象上wait, 也不由同一个对象唤醒
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 如果线程1竞争到了lock, 也通过了state判定, 将执行打印任务
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
// 打印完成后将state赋值为2, 表示下一次的打印任务将由线程2执行
state = 2;
// 唤醒在c2分支上wait的线程2,这实际上是指定唤醒了线程2,线程3不会被唤醒。
c2.signal();
} finally {
// 打印任务执行完成后需要确保锁被释放, 因此将释放锁的代码放在finally中
lock.unlock();
}
}
}
}, "线程1").start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
lock.lock();
while (state != 2)
try {
c2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
state = 3;
c3.signal();
} finally {
lock.unlock();
}
}
}
}, "线程2").start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
lock.lock();
while (state != 3)
try {
c3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName()
+ ": " + n++);
}
System.out.println();
state = 1;
c1.signal();
} finally {
lock.unlock();
}
}
}
}, "线程3").start();
}
public static void main(String[] args) {
new NumberPrint().run();
}
}