Runnable接口与Thread类
创建线程的两种方法
用户线程与守护线程
线程同步机制
public class BufferLock{
private int value = 0;
private boolean isEmpty = true;
public BufferLock(){ //构造方法
this.value = 0;
this.isEmpty = true;
}
/* 成员方法,操作数据;加互斥锁 */
public synchronized void put(int value){
while(isEmpty == false){ //状态非空时:持续等待
try{
this.wait();
}catch(InterruptedException e){}
}
//状态空时:写入数据,先置标志位为非空,再唤醒其他进程
this.value = value;
isEmpty = false;
notify();
}
public synchronized int get(){
while(isEmpty == true){ //状态为空时:持续等待
try{
this.wait();
}catch(InterruptedException e){}
}
//状态非空时:获取数值,先置标志位空,再唤醒其他进程
int temp = value;
isEmpty = true;
notify();
return temp;
}
}
/*发送进程类*/
class Sender extends Thread{
private BufferLock bufferLock = null;
public Sender(BufferLock bufferLock){ //构造方法
this.bufferLock = bufferLock;
}
public void run(){
for(int i=0 ;i<10 ;i++){
bufferLock.put(i);
System.out.println("send:"+i);
}
}
}
/*接收进程类*/
class Receiver implements Runnable{
private BufferLock bufferLock = null;
public Receiver(BufferLock bufferLock){
this.bufferLock = bufferLock;
}
public void run(){
for(int i=0 ; i<10 ; i++){
System.out.println("\t\t receive:"+bufferLock.get());
}
}
}
/*测试类*/
class Test{
public Test(){
super();
}
public static void main(String args[]){
BufferLock bufferLock = new BufferLock();
Sender sender = new Sender(bufferLock);
sender.start();
Receiver receiver = new Receiver(bufferLock);
new Thread(receiver).start();
}
}