0
Follow
0
View

Can someone help me to look at how to write, changed many times feel wrong

rendongxing9 注册会员
2023-02-27 23:45

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

cyj773 注册会员
2023-02-27 23:45

// defines employee threads where the keyword synchronized is a lock and only one thread can access the printer ata time

public class MyThread extends Thread {

      private int count=5; 
        @Override 
        synchronized  public void run()
        { 
            super.run(); 
            count--; 
            //此示例不要用for语句,因为使用同步后其他线程就得不到运行的机会了, 
            //一直由一个线程进行减法运算 
            System.out.println("count="+count); 
        }
    }

// Start the thread,

public class Test {
    public static void main(String[] args)
    { 
        MyThread mythread=new MyThread(); 
        Thread a=new Thread(mythread,"A"); 
        Thread b=new Thread(mythread,"B"); 
        Thread c=new Thread(mythread,"C"); 
        a.start(); 
        b.start(); 
        c.start(); 
    }
}

All three threads run at the same time and print different results.
If synchronized is not added, the printed result may have the same value.

About the Author

Question Info

Publish Time
2023-02-27 23:45
Update Time
2023-02-27 23:45