多线程实例—设计一个生产电脑和搬运电脑类......

设计一个生产电脑和搬运电脑的类,要求生产出一台电脑就搬走一台电脑,
如果没有新的电脑生产出来,则搬运工要等待新电脑产出;如果生产出来的电脑没有搬走,
则要等待电脑搬走之后再生产,并统计出生产的电脑数量

package chapter9;

class Computer{
private String name=“thinkpad”;
private static int sum =1;
private boolean flag =false;
public synchronized void set() {
if(flag)
{
try {
super.wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(“生产了一台”+name+",现在已经生产了"+sum+“台电脑”);
sum++;
flag=true;
super.notify();
}
public synchronized void get() {
if(!flag)
{
try {
super.wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
}
catch(InterruptedException e) {
e.printStackTrace();
}
flag=false;
super.notify();
System.out.println(“搬走了一台”+name);
}
}
class made implements Runnable{
private Computer computer=null;
public made(Computer computer) {
this.computer=computer;
}
public void run()
{
for(int i=0;i<10;i++)
{
this.computer.set();
}
}
}
class move implements Runnable{
private Computer computer=null;
public move(Computer computer) {
this.computer=computer;
}
public void run()
{
for(int i=0;i<10;i++)
{
this.computer.get();
}
}
}
public class Test{
public static void main(String args[]) {
Computer c=new Computer();
made t1=new made©;
move t2=new move©;
new Thread(t1).start();
new Thread(t2).start();
}
}

你可能感兴趣的:(java基础)