日期:2014-05-19  浏览次数:20677 次

java线程睡眠问题
这是我的代码
package org.com.JframeDemo;

public class ControlClass {
private int readCount; // 需要读的读者
private int writeCount; // 需要写的写者
private boolean cRead; // 读者的状态
private boolean cWrite; // 学者的状态
public static int a;

public ControlClass() { // 初始化数据
readCount = 0;
writeCount = 0;
cRead = false;
cWrite = false;
}

public static void sleeptime() { // 睡眠时间
int sleepTime = (int) (Math.random());
try {
Thread.sleep(sleepTime * 10000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

public synchronized void startRead() { // 读者开始读取
if (cRead == false) {
while (writeCount > 0) { // 写者优先
try {
a=0;
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
e.printStackTrace();
}
}
}
readCount++;
if (readCount == 1) {
cRead = true; // 返回有读者正在读
}
}

public synchronized void endRead() { // 读者结束读取
--readCount;
if (readCount == 0) {
cRead = false;
}
notifyAll(); // 释放空间

}

public synchronized void startWrite() { // 写者开始写
writeCount++;
if (cRead == true || cWrite == true) {
a=1;
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
e.printStackTrace();
}
}
cWrite = true;
}

public synchronized void endWrite() {
writeCount++;
cWrite = false;
notifyAll();
}
}


package org.com.JframeDemo;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTextArea;

public class Reader implements Runnable {
private ControlClass controlClass;
private JTextArea t;
private int reader;
public static String str = "",time1,time2;

public Reader(int reader, JTextArea t, ControlClass controlClass) {
this.reader = reader;
this.t = t;
this.controlClass = controlClass;
}

@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
    final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 
    time1 = format.format(new Date());
str = time1+"读者" + reader + "准备读取" + '\n';
t.append(str);
controlClass.startRead(); // 读者开始工作
str = "读者" + reader + "正在读取" + '\n';