学而不思则罔,思而不学则殆
这个主要考虑的是线程同锁
第一种实现
使用关键字synchronized
public static void main(String[] args) {
int[] values = new int[]{'A', 1};
new Thread(new DiyRunnable1(values, 1)).start();
new Thread(new DiyRunnable1(values, 2)).start();
new Thread(new DiyRunnable1(values, 3)).start();
}
public static class DiyRunnable1 implements Runnable {
final int[] values;
int tag;
public DiyRunnable1(int[] values, int tag) {
this.values = values;
this.tag = tag;
}
public void run() {
while (values[0] <= 'Z') {
synchronized (values) {
try {
if (tag == values[1]) {//tag相等
System.out.println(tag + " " + (char) values[0]);
values[0] = values[0] + 1; //需要打印的下一个字符
values[1] = (values[1]) % 3 + 1; //设置需要打印的下一个的tag 1 2 3
values.notifyAll(); //唤醒等待中的线程
} else {
values.wait(); //tag不等,等待,释放锁
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (values) {
values.notifyAll();
}
}
}
第二种实现
private static void test11() {
int[] values = new int[]{'A', 1};
new Thread(new DiyRunnable11(values, 1)).start();
new Thread(new DiyRunnable11(values, 2)).start();
new Thread(new DiyRunnable11(values, 3)).start();
}
public static class DiyRunnable11 implements Runnable {
final int[] values;
int tag;
public DiyRunnable11(int[] values, int tag) {
this.values = values;
this.tag = tag;
}
public void run() {
while (values[0] <= 'Z') {
synchronized (values) { //竞争锁
if (values[0] > 'Z'){
return;
}
if (tag == values[1]) {
System.out.println(tag + " " + (char) values[0]);
values[0] = values[0] + 1; //需要打印的下一个字符
values[1] = (values[1]) % 3 + 1; //设置需要打印的下一个的tag 1 2 3
}
}
}
}
}
第三种实现
public static class DiyRunnable2 implements Runnable {
ReentrantLock mReentrantLock;
int mTag;
Bean mBean;
public DiyRunnable2(ReentrantLock reentrantLock, int tag, Bean bean) {
this.mReentrantLock = reentrantLock;
this.mTag = tag;
this.mBean = bean;
}
public static class Bean {
int tag;
int ch;
public Bean(int tag, int ch) {
this.tag = tag;
this.ch = ch;
}
}
public void run() {
while (mBean.ch <= 'Z') {
try {
mReentrantLock.lock(); //获取锁
if (mBean.ch > 'Z') {
return;
}
if (mBean.tag == mTag) {
System.out.println(mTag + " " + (char) mBean.ch);
//打印的字符加1
mBean.ch++;
//tag转换为下一个
mBean.tag = mBean.tag % 3 + 1;
}
} finally {
mReentrantLock.unlock();//释放锁
}
}
}
}
private static void test2() {
ReentrantLock reentrantLock = new ReentrantLock();
DiyRunnable2.Bean bean = new DiyRunnable2.Bean(1, 'A');
new Thread(new DiyRunnable2(reentrantLock, 1, bean)).start();
new Thread(new DiyRunnable2(reentrantLock, 2, bean)).start();
new Thread(new DiyRunnable2(reentrantLock, 3, bean)).start();
}