使用线程挑战Java程序

时间:2015-09-25 10:16:27

标签: java multithreading

帮助搞清楚这个编码问题:在这家公司,他们是3个分支机构,每个分支机构有3台计算机。该网络具有中央路由器,可将计算机连接到正确的数据存储和打印机。所有打印数据和存储检索数据都必须通过路由器。该路由器是单处理器。制作一个类路由器。然后写一个刺激来测试你的路由器代码。为路由器上的每个端口创建一个线程,并同时启动它们。通过以下调用刺激功能。

作业(PB,1,d,60000)

作业(PB,3,P,100000)

作业(PB,2,d,75000)

作业(FB,1,P,30000)

作业(FB,2,d,150000)

作业(FB,3,P,89000)

作业(MB,1,P,200000)

作业(MB,2,d,140000)

作业(MB,3,P,1350000)

作业(分支,计算机端口,D =数据P =打印,字符数)

完成所有运行后,让路由器软件按分支打印以下内容:

  1. 处理的数据字符数和处理成本。

  2. 处理的打印字符数和处理成本。

  3. 3处理的字符总数和处理总成本。

    费用计算如下:

    1. 生产部门;打印连接0.007美分/字符,数据连接0.008美分/字符

    2. 财务科;打印连接0.009美分/字符,数据连接0.007美分/字符

    3. 营销科;打印连接0.0095美分/字符,数据连接0.0082

      import java.io. ;  import java.io.IOException;  import javax.swing。;  import java.util。;  import java.io.File;  import java.io.FileNotFoundException;  import java.lang.IllegalStateException;  import java.util.NoSuchElementException;  import java.lang。;  // import java.lang.Thread; //这允许运行线程  import java.util.concurrent。; //这允许创建一个可以全部启动的线程池 //一个执行人执行人 import java.util.concurrent.locks。; //这使我能够锁定一个函数

      public class Homework_02 {
      public static void main(String[] args) throws Exception {
      
       //Create PrintWriter for separate output
       PrintWriter outf1;
       outf1=new PrintWriter(new File("Homework_02Out.txt"));
      
       //create thread pool without executor
       //Production Branch
       Runnable printPB1=new Job("PB",1,'D',60000);
       Runnable printPB3=new Job("PB",3,'P',100000);
       Runnable printPB2=new Job("PB",2,'D',75000);
      
       //Financial Branch
       Runnable printFB1=new Job("FB",1,'P',30000);
       Runnable printFB2=new Job("FB",2,'D',150000);
       Runnable printFB3=new Job("FB",3,'P',89000);
      
        //Marketing Branch
        Runnable printMB1=new Job("MB",1,'P',200000);
        Runnable printMB2=new Job("MB",2,'D',140000);
      Runnable printMB3=new Job("MB",3,'P',135000);
      
      //Create Threads
      Thread thread1=new Thread(printPB1);
      Thread thread2=new Thread(printPB2);
      Thread thread3=new Thread(printPB3);
      Thread thread4=new Thread(printFB1);
      Thread thread5=new Thread(printFB2);
      Thread thread6=new Thread(printFB3);
      Thread thread7=new Thread(printMB1);
      Thread thread8=new Thread(printMB2);
      Thread thread9=new Thread(printMB3);
      
      /*Prioritize (if needed)
      thread1.setPriority(Thread.MAX_PRIORITY);
      thread2.setPriority(Thread.MAX_PRIORITY);
      thread3.setPriority(Thread.MAX_PRIORITY);
      thread4.setPriority(Thread.MAX_PRIORITY);
      thread5.setPriority(Thread.MAX_PRIORITY);
      thread6.setPriority(Thread.MAX_PRIORITY);
      thread7.setPriority(Thread.MAX_PRIORITY);
      thread8.setPriority(Thread.MAX_PRIORITY);
      thread9.setPriority(Thread.MAX_PRIORITY);
      */
      
      //Now start the threads
      thread1.start();
      thread2.start();
      thread3.start();
      thread4.start();
      thread5.start();
      thread6.start();
      thread7.start();
      thread8.start();
      thread9.start();
      
      //flush(if needed)
      outf1.flush();
      }
      
      
      }
      
      class Job implements Runnable{
      private String branch;
      private int port;
      private static char type;
      private static double characters;
      
      public Job(String b, int x, char t, double num){
      branch=b;
      port=x;
      type=t;
      characters=num;
      }
      
      public void run() {
      // TODO Auto-generated method stub
      
      }
      }
      

1 个答案:

答案 0 :(得分:1)

可能不是所要求的,因为我没有看到线程的需要,但我还是使用了线程。我还使用Lock来演示它们是如何工作的,但我也使用了Atomic s,因此锁可能不是必需的。

enum Branch {

    Production(0.007, 0.008),
    Financial(0.009, 0.007),
    Marketing(0.0095, 0.0082);
    // PB/FB/MB
    final String id = name().charAt(0) + "B";
    // Costs.
    final double printCost;
    final double dataCost;

    private Branch(double printCost, double dataCost) {
        this.printCost = printCost;
        this.dataCost = dataCost;
    }

    // One lock for each computer at this branch.
    Lock[] computers = new Lock[3];

    {
        for (int i = 0; i < computers.length; i++) {
            computers[i] = new ReentrantLock();
        }
    }

    public void lock(int computer) {
        computers[computer - 1].lock();
    }

    public void unlock(int computer) {
        computers[computer - 1].unlock();
    }

    AtomicInteger dataProcessed = new AtomicInteger();

    public void data(int amount) {
        dataProcessed.addAndGet(amount);
    }

    AtomicInteger printProcessed = new AtomicInteger();

    public void print(int amount) {
        printProcessed.addAndGet(amount);
    }

    public static Branch lookup(String id) {
        for (Branch b : Branch.values()) {
            if (b.id.equals(id)) {
                return b;
            }
        }
        return null;
    }

    private void printStats() {
        System.out.println("Branch " + name()
                + " processed " + dataProcessed
                + " cost=" + (dataProcessed.get() * dataCost)
                + " printed " + printProcessed
                + " cost=" + (printProcessed.get() * printCost)
        );
    }

}

enum Function {

    Data {

                @Override
                void function(Branch b, int size) {
                    b.data(size);
                }
            },
    Print {
                @Override
                void function(Branch b, int size) {
                    b.print(size);
                }
            };
    // D/P
    final String id = "" + name().charAt(0);

    public static Function lookup(String id) {
        for (Function b : Function.values()) {
            if (b.id.equals(id)) {
                return b;
            }
        }
        return null;
    }

    abstract void function(Branch b, int size);
}

class Router {

    public void job(String branch, int computer, String function, int size) {
        Branch b = Branch.lookup(branch);
        // Grab the lock on that computer at that branch.
        b.lock(computer);
        try {
            Function f = Function.lookup(function);
            f.function(b, size);
        } finally {
            b.unlock(computer);
        }
    }

    private void job(Job j) {
        job(j.branch, j.computer, j.function, j.data);
    }

    private void printStats() {
        // For all branches:
        for (Branch b : Branch.values()) {
            b.printStats();
        }
    }
}
// Just one router.
final Router router = new Router();

class Job implements Runnable {

    String branch;
    int computer;
    String function;
    int data;

    public Job(String branch, int computer, String function, int data) {
        this.branch = branch;
        this.computer = computer;
        this.function = function;
        this.data = data;
    }

    @Override
    public void run() {
        router.job(this);
    }

}

public void test() throws InterruptedException {
    System.out.println("Hello");
    Job[] jobs = {
        new Job("PB", 1, "D", 60000),
        new Job("PB", 3, "P", 100000),
        new Job("PB", 2, "D", 75000),
        new Job("FB", 1, "P", 30000),
        new Job("FB", 2, "D", 150000),
        new Job("FB", 3, "P", 89000),
        new Job("MB", 1, "P", 200000),
        new Job("MB", 2, "D", 140000),
        new Job("MB", 3, "P", 1350000)};
    Thread[] threads = new Thread[jobs.length];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(jobs[i]);
        threads[i].start();
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
    }
    router.printStats();
}

打印:

Branch Production processed 135000 cost=1080.0 printed 100000 cost=700.0
Branch Financial processed 150000 cost=1050.0 printed 119000 cost=1071.0
Branch Marketing processed 140000 cost=1148.0 printed 1550000 cost=14725.0

请注意 - 作为专业开发人员,我发布专业级代码。请不要试图将它呈现给您的老师,就好像它是您的一样。他们会马上知道事实并非如此。

您应该使用此代码来了解您可以使用的技术。