/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg20221204stackthreaddemo;
import java.util.Stack;
/**
*
* @author mikha
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Stack<Integer> stack=new Stack<>();
// stack.setSize(3);
//两个线程一个读一个写
WriteThread writeThread=new WriteThread(stack);
writeThread.setName("写线程");
ReadThread readThread=new ReadThread(stack);
readThread.setName("读线程");
writeThread.start();
readThread.start();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg20221204stackthreaddemo;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author mikha
*/
public class ReadThread extends Thread{
private Stack<Integer> stack;
private int count;
public ReadThread(Stack<Integer> stack) {
this.stack = stack;
count = 1;
}
@Override
public void run() {
System.out.println("写线程在运行");
while(count<=100)
{
synchronized(stack)
{
if(stack.empty())
{
try {
stack.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ReadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
else//栈不空
{
int data=stack.pop();
System.out.println(Thread.currentThread().getName()+"读出:"+data);//输出读出的是几
count++;
stack.notify();
}
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg20221204stackthreaddemo;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author mikha
*/
public class WriteThread extends Thread{
private Stack<Integer>stack;
private int count;//线程中的个数
public WriteThread(Stack<Integer> stack) {
this.stack = stack;
count=1;
}
@Override
public void run() {
System.out.println("写线程正在运行");
while(count<=100)
{
synchronized(stack)//Syncronized 的目的是一次只允许一个线程进入由他修饰的代码段,从而允许他们进行自我保护
{
if(stack.size()==3)//栈满
{
try {
stack.wait();//等待
} catch (InterruptedException ex) {
Logger.getLogger(WriteThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
stack.push(count);
System.out.println(Thread.currentThread().getName()+"写入:"+count);//输出写入的是几
count++;
stack.notify();//Object notify() 方法用于唤醒一个在此对象监视器上等待的线程。
}
}
}
}
}