📄 common.java
字号:
package com.test;
public class common
{
private char ch;
private boolean available = false;
synchronized char get()
{
while(available==false)
{
try
{
wait();
}catch(InterruptedException e){}
available = false;
notify();
return ch;
}
return ch;
}
synchronized void put(char newch)
{
while(available==true)
{
try
{
wait();
}catch(InterruptedException e){}
ch = newch;
available = true;
notify();
}
}
//生产者线程
static class producer extends Thread
{
private common comm;
public producer(common thiscomm)
{
comm = thiscomm;
}
public void run()
{
for(char c='a';c<='e';c++)
{
System.out.println("生产的数据是:"+c);
comm.put(c);
}
}
};
//消费者线程
static class consumer extends Thread
{
private common comm;
public consumer(common thiscomm)
{
comm = thiscomm;
}
public void run()
{
char c;
for(int i=0;i<5;i++)
{
c = comm.get();
System.out.println("消费者得到的数据是:"+c);
}
}
};
public static void main(String arg[])
{
common comm = new common();
producer p = new producer(comm);
consumer s = new consumer(comm);
p.start();
s.start();
}
};
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -