Java教程-静态同步

静态同步
如果将任何静态方法声明为同步方法,锁将在类上而不是对象上。
静态同步的问题
假设有一个共享类(例如Table)的两个对象object1和object2。在使用同步方法和同步块的情况下,t1和t2或t3和t4之间不能产生干扰,因为t1和t2都引用了一个具有单个锁的公共对象。但是t1和t3之间或t2和t4之间可能会有干扰,因为t1获取了另一个锁,t3获取了另一个锁。我们不希望t1和t3之间或t2和t4之间发生干扰。静态同步解决了这个问题。
静态同步的示例
在此示例中,我们在静态方法上使用synchronized关键字进行静态同步。
TestSynchronization4.java
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();
}
}
输出:
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
使用匿名类进行静态同步的示例
在此示例中,我们使用匿名类创建线程。
TestSynchronization5.java
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();
}
}
输出:
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中的静态同步方法printTable(int n)相当于以下声明:
static void printTable(int n) {
synchronized (Table.class) { // A类同步块
// ...
}
}