直播软件开发,synchronized关键字

发布时间 2023-06-01 14:13:05作者: 云豹科技-苏凌霄

直播软件开发,synchronized关键字

public class Test {
 
    public static void main(String[] args) {
        Count obj = new Count();//only one object
        MyThread1 t1 = new MyThread1(obj);
        MyThread2 t2 = new MyThread2(obj);
        t1.start();
        t2.start();
    }
}
 
class MyThread2 extends Thread {
    Count c;
 
    MyThread2(Count c) {
        this.c = c;
    }
 
    public void run() {
        c.printTable(100);
    }
}
 
class MyThread1 extends Thread {
    Count c;
 
    MyThread1(Count c) {
        this.c = c;
    }
 
    public void run() {
        c.printTable(5);
    }
 
 
}
 
class Count {
    //加和不加的打印区别
    public synchronized void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                //睡眠四秒
                Thread.sleep(400);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
 
    }
}

​ 以上就是直播软件开发,synchronized关键字, 更多内容欢迎关注之后的文章