- 首页 > it技术 > >
/**
* 基于一个锁和一个状态变量实现连续打印abcabc...
* @author lixiaoxi
*
*/
public class StateLockPrinter {
//状态变量
private volatile int state=0;
// 打印线程
private class Printer implements Runnable {
//打印次数
private static final int PRINT_COUNT=2;
//打印锁
private final Object printLock;
//打印标志位 和state变量相关
private final int printFlag;
//后继线程的线程的打印标志位,state变量相关
private final int nextPrintFlag;
//该线程的打印字符
private final char printChar;
public Printer(Object printLock, int printFlag,int nextPrintFlag, char printChar) {
super();
this.printLock = printLock;
this.printFlag=printFlag;
this.nextPrintFlag=nextPrintFlag;
this.printChar = printChar;
}@Override
public void run() {
//获取打印锁 进入临界区
synchronized (printLock) {
//连续打印PRINT_COUNT次
for(int i=0;
i【循环打印abcabc】
推荐阅读