Java线程学习最经典的例子-读写者,主要用到Thread相关知识如下:
-线程的start与run
-线程的休眠(sleep)
-数据对象加锁(synchronized)
-数据对象的等待与释放(wait and notify)
程序实现:
-ObjectData数据类对象,通过synchronized关键字实现加锁,在线程读写者中使用。
-ConsumerThread消费者线程,读取数据对象中count值之后,通知生产者线程
-ProductThread生产者线程,对数据对象中count
一:实体类
public class ObjectData {
private int count;
public ObjectData(){
count=0;
}
public void read(){
System.out.println("read count :" + count);
System.out.println();
}
public void write(){
count++;
System.out.println("write count :" + count);
}
}
二:生产者
public class ProductThread extends Thread{
private ObjectData data;
public ProductThread(ObjectData data) {
this.data = data;
}
@Override
public void run() {
while (true) {
try {
synchronized (data) {
data.write();
Thread.sleep(3000);
System.out.println(1);
data.notify();//数据对象的释放
System.out.println(2);
data.wait();//数据对象的等待
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
三:消费者
public class ConsumerThread extends Thread{
private ObjectData data;
public ConsumerThread(ObjectData data){
this.data=data;
}
@Override
public void run() {
while(true) {
try {
synchronized (data) {
System.out.println(3);
data.wait();
System.out.println(4);
data.read();
System.out.println(5);
data.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
四:测试类
public class Test {
public static void main(String[] args) {
ObjectData data = new ObjectData();
ConsumerThread ct = new ConsumerThread(data);
ProductThread pt = new ProductThread(data);
ct.start();
pt.start();
}
转载:来源:流浪的鱼
}