Java教程

Java 线程静态同步

如果将任何静态方法设置为已同步,则锁定将锁定在类上而不是对象上。
静态同步

没有静态同步的问题

假设有两个共享类(例如表)的对象名为object1和object2。在使用同步方法和同步块的情况下,t1和t2或t3和t4之间不会存在干扰,因为t1和t2均指的是具有单个锁的公共对象。但是t1和t3或t2和t4之间可能存在干扰,因为t1获得了另一个锁而t3获得了另一个锁,我希望t1和t3或t2和t4之间没有干扰,静态同步解决了这个问题。

静态同步的示例

在此示例中,我们将static关键字应用于static方法以执行静态同步。
class Table{
    synchronized static void printTable(int n){
        for(int i=1;i<=10;i++){
            System.out.println(n*i);
            try{
                Thread.sleep(400);
            }
            catch(Exception e){
            }
        }
    }
}
class MyThread1 extends Thread{
    public void run(){
        Table.printTable(1);
    }
}
class MyThread2 extends Thread{
    public void run(){
        Table.printTable(10);
    }
}
class MyThread3 extends Thread{
    public void run(){
        Table.printTable(100);
    }
}
class MyThread4 extends Thread{
    public void run(){
        Table.printTable(1000);
    }
}
public class TestSynchronization4{
    public static void main(String t[]){
        MyThread1 t1=new MyThread1();
        MyThread2 t2=new MyThread2();
        MyThread3 t3=new MyThread3();
        MyThread4 t4=new MyThread4();
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

通过匿名类进行静态同步的相同示例

在此示例中,我们使用匿名类创建线程。
class Table{
    synchronized static void printTable(int n){
        for(int i=1;i<=10;i++){
            System.out.println(n*i);
            try{
                Thread.sleep(400);
            }
            catch(Exception e){
            }
        }
    }
}
public class TestSynchronization5 {
    public static void main(String[] args) {
        Thread t1=new Thread(){
            public void run(){
                Table.printTable(1);
            }
        }
        ;
        Thread t2=new Thread(){
            public void run(){
                Table.printTable(10);
            }
        }
        ;
        Thread t3=new Thread(){
            public void run(){
                Table.printTable(100);
            }
        }
        ;
        Thread t4=new Thread(){
            public void run(){
                Table.printTable(1000);
            }
        }
        ;
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

类锁上的同步块:

该块在由引用.class名称.class表示的对象的锁上同步。类Table中的静态同步方法printTable(int n)等效于以下声明:
static void printTable(int n) {
    synchronized (Table.class) {
        // synchronized block on class A
    // ...
    }
}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4