JAVA多线程两道练习题

一,JAVA设计四个线程对象,两个线程执行加操作,两个线程执行减操作

package one;
 import java.io.*;
public class one1 implements Runnable{ 
  private static int count=0;
  public void run()
  {
   while(true)
   {
    if(Thread.currentThread().getName().startsWith("add"))
     count++;
    else
     count--;
    System.out.print(count);
   try{
    Thread.sleep(500);
   }catch(Exception e){
    e.printStackTrace();
   }
  }
  }
 public static void main(String[] args) throws Exception {
  one1 test=new one1();
  Thread t1=new Thread(test,"add1");
  Thread t2=new Thread(test,"add2");
  Thread t3=new Thread(test,"mul1");
  Thread t4=new Thread(test,"mul2");
  t1.start();
  t2.start();
  t3.start();
  t4.start();
 }
}

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

 package one;
 class Computer
 {
  private int sum=0;
  private boolean flag=false;
  private String name="thinkPad";
  public synchronized void set(){//synchronized是同步码
   if(flag){
    try{
     super.wait();
    }catch(Exception e){
     e.printStackTrace();
    }
   }
   try{
    Thread.sleep(1000);
   }catch(Exception e){
    e.printStackTrace();
   }
   sum++;
   System.out.print("生产了"+sum+"台"+name+"电脑      ");
   flag=true;
   super.notify();
  }
  public synchronized void get()
  {
   if(!flag){
    try{
     super.wait();
    }catch(Exception e){
     e.printStackTrace();
    }
   }
   try{
    Thread.sleep(1000);
   }catch(Exception e){
    e.printStackTrace();
   }
   System.out.print("搬走了一台"+name+"\n");
   flag=false;
   super.notify();//解除wait()方法的冻结
  }
 }
 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 one1 { 
 public static void main(String[] args) throws Exception {
  Computer c=new Computer();
  made m1=new made(c);
  Thread t1=new Thread(m1);
  move m2=new move(c);
  Thread t2=new Thread(m2);
  t1.start();
  t2.start();
 }
}

运行结果:
JAVA多线程两道练习题_第1张图片

你可能感兴趣的:(JAVA学习)