Java 静态同步方法

1 什么是Java静态同步方法

如果将任何静态方法设置为synchronized(同步),则锁定的是类而不是对象

2 没有静态同步方法的问题

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

3 静态同步方法的例子1

在此示例中,我们将static关键字应用于static方法以执行静态同步。

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * 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 Demo{
    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();
    }
}

输出结果为:

10
20
30
40
50
60
70
80
90
100
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
100
200
300
400
500
600
700
800
900
1000
1
2
3
4
5
6
7
8
9
10

4 静态同步方法的例子2

在此示例中,我们使用匿名类创建线程。

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * 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 Demo {
    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
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
100
200
300
400
500
600
700
800
900
1000
10
20
30
40
50
60
70
80
90
100

 

热门文章

优秀文章