我在这里遇到了一个小问题。我正在用 Java 做一个并发程序。问题是:有 4 个人(学生)试图访问打印机,打印 5 个文档。但当时只有一个可以打印(很明显)5 个文件。当他们完成时,他们通知其他人他们已经完成并且其他线程访问该资源。我有一个主类,学生类和监视器(激光打印机),文档类,其中包含有关文档的信息,例如(页数,名称用户 ID 等)+ 一些打印机接口。我已经成功地运行了线程,但它们不同步(互斥)
所以问题是我如何实现互斥(当时只有一个人可以打印他的文档数量)
感谢您的关注、时间和提示: )
主班
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();
学生班
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");
监控类
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);
}