java SE基础(多线程)

Runnable接口与Thread类

java SE基础(多线程)_第1张图片

创建线程的两种方法

java SE基础(多线程)_第2张图片

用户线程与守护线程

java SE基础(多线程)_第3张图片

线程同步机制

java SE基础(多线程)_第4张图片

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();
	}	
}



你可能感兴趣的:(java,多线程,线程)