简体   繁体   English

如何在此应用程序中使用同步方法实现互斥

[英]how to achieve mutual exclusion using synchronized method in this application

i have run into a little problem in here. 我在这里遇到了一个小问题。 I am doing a concurrent program in Java. 我正在用Java执行并发程序。 Problem is: There are 4 people (students) that are trying to access printer, to print 5 documents. 问题是:有4个人(学生)试图访问打印机,以打印5个文档。 But only one can print at the time (kind of obvious) 5 documents. 但是当时(很明显)只能打印5张文件。 When they finish they notify other that they done and other thread accesses the resource. 完成后,他们会通知其他人已完成操作,并且其他线程将访问该资源。 i have a Main class, student class and Monitor (laser printer), Document class that holds info about the document like (number of pages, name user id etc)+ few interfaces for printer. 我有一个主班,一个学生班和一个监视器(激光打印机),一个文档班,保存有关文档的信息,例如(页数,名称用户ID等)+打印机的几个接口。 I have managed to run successfully threads but they are not synchronized (mutual exclusion) 我已经成功运行了线程,但是它们没有同步(互斥)
So the question is how do i achieve mutual exclusion ( that only one person can print at the time his number of docs) 所以问题是我如何实现互斥(在文档数量时只有一个人可以打印)
Thank you for looking, time and hints :) 感谢您的关注,时间和提示:)

Main class 主班

    String S1Name = "bob";
    String S2Name = "klara";
    String S3Name = "John";
    String S4Name = "Iga";

    String T1Name = "Man";
    String T2Name = "Woman";


    final int NoOfDocs = 5;
    ServicePrinter sp = new LaserPrinter();

    ThreadGroup groupA = new ThreadGroup("Group A"); 
    ThreadGroup groupB = new ThreadGroup("Group B");

    Student student1 = new Student(sp,NoOfDocs,S1Name, groupA);
    Student student2 = new Student(sp,NoOfDocs,S2Name, groupA);
    Student student3 = new Student(sp,NoOfDocs,S3Name, groupA);
    Student student4 = new Student(sp,NoOfDocs,S4Name, groupA);

    TonerTechnician TT = new TonerTechnician(groupB);
    PaperTechnician PT = new PaperTechnician(groupB);

    /*
     * Start Student Threads
     */
    student1.start();
    student2.start();
    student3.start();
    student4.start();

    /*
     * Start Technician threads
     */
    TT.start();
    PT.start();

Student Class 学生班

 private final ServicePrinter serviceprinter;
    private final int NoOfDocs;
    private final String Name;
    private final ThreadGroup threadgroup;

    public Student(ServicePrinter serviceprinter, int NoOfDocs, String Name, ThreadGroup threadgroup)
    {
        this.serviceprinter = serviceprinter;
        this.NoOfDocs = NoOfDocs; 
        this.Name = Name;
        this.threadgroup = threadgroup;
    }
    @Override
    public void run()
    {
        /*
         * each students prints 5 documents (different name and length)
         */
        final LaserPrinter lp = new LaserPrinter();
        //sleep from 1 to 5 sec random time
        final Random random = new Random();       
        char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();
        /*
         * Create random document name 10 characters long
         */
        for (int i = 0; i < 10; i++) 
        {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String docName  = sb.toString();
        /*
         * print 5 documents (random sleep time between printing)
         */
        for(int i = 0; i < NoOfDocs; i++)
        {
            try 
            {
                Document coursework = new Document(Name,docName,random.nextInt(90)+10);
                lp.printDocument(coursework);
                Thread.sleep(random.nextInt(1000)+4000);                
            } 
            catch (InterruptedException ex) 
            {
                Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
            }            
        }
        System.out.println("User: " + Name+ " completed printing");

Monitor class 班长班

    int tonerLevel = 500;
    int paperLevel = 250;

    private final String PrinterName = "HP";
    private final String PrinterID = "LX-440";
    private int CurrentPaperLevel;
    private int CurrentTonerLevel;
    private int NoOfDocsPrinted;

    @Override
    public synchronized void printDocument(Document document) {
        System.out.println(document);

    }

Here is a simple mutex implementation but you should use java.util.concurrent package for synchronization 这是一个简单的互斥量实现,但是您应该使用java.util.concurrent包进行同步

EDIT: Changed mutex to semaphore (it makes more sense) 编辑:将互斥量更改为信号量(更有意义)

A simple mutex implementaion: 一个简单的互斥体实现:

public class Mutex {

    private int semaphore;

    public synchronized void aquire() throws InterruptedException {

        if(semaphore < 0) {
            wait();
        }

        semaphore--;

    }

    public synchronized void release() {

        if(semaphore < 0) {
            semaphore++;
            notify();            
        }
    }
}

It seems that you're creating a local printer object in your run method instead of using the shared one you pass to the Student class. 看来您是在run方法中创建本地打印机对象,而不是使用传递给Student类的共享对象。 Try using the shared printer that you pass and see what you get. 尝试使用通过的共享打印机,看看会得到什么。 Also we need to see how you use printDocument in ServicePrinter . 另外,我们还需要了解如何在ServicePrinter使用printDocument This is because you are using a ServicePrinter object in your Student class, and the implementation of printDocument in ServicePrinter may not be correct (that is if you actually have it implemented in the superclass) 这是因为您在Student类中使用了ServicePrinter对象,并且ServicePrinterprintDocument的实现可能不正确(也就是说,如果您实际上在超类中实现了它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM