java线程睡眠分析,java线程睡眠有关问题

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';

t.append(str);

ControlClass.sleeptime(); // 读者处于工作阶段

controlClass.endRead(); // 读者结束读取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值