Create three classes, a main class, a Printer class, and a Thread class.
main class:
public class main {
public static void main(String[] args) {
Printer printer = new Printer();
new Thread(new Employee("李强", printer)).start();
new Thread(new Employee("王晓", printer)).start();
new Thread(new Employee("陈明", printer)).start();
}
}
Printer class
class Printer {
public synchronized void print(String name) {
System.out.print(name + "正在使用打印机");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + "使用完毕");
}
}
Employee class:
public class Employee implements Runnable {
private final String name;
private final Printer printer;
public Employee(String name, Printer printer) {
this.name = name;
this.printer = printer;
}
@Override
public void run() {
printer.print(name);
}
}
There you go