Java教程

Java 同步块

同步块可用于对方法的任何特定资源执行同步。
假设您有50行代码您的方法,但只想同步5行,则可以使用同步块。
如果将方法的所有代码都放在同步块中,它将与同步方法一样工作。

同步块要记住的点

同步块用于锁定任何共享资源的对象。 同步块的范围小于方法。
使用同步块的语法
synchronized (object reference expression) {
//code block }

同步块示例

让我们看一下同步块的简单示例。
同步块程序
class Table{
    void printTable(int n){
        synchronized(this){
            //synchronized block for(int i=1;i<=5;i++){
                System.out.println(n*i);
                try{
                    Thread.sleep(400);
                }
                catch(Exception e){
                    System.out.println(e);
                }
            }
        }
    }
//end of the method}
class MyThread1 extends Thread{
    Table t;
    MyThread1(Table t){
        this.t=t;
    }
    public void run(){
        t.printTable(5);
    }
}
class MyThread2 extends Thread{
    Table t;
    MyThread2(Table t){
        this.t=t;
    }
    public void run(){
        t.printTable(100);
    }
}
public class TestSynchronizedBlock1{
    public static void main(String args[]){
        Table obj = new Table();
        //only one objectMyThread1 t1=new MyThread1(obj);
        MyThread2 t2=new MyThread2(obj);
        t1.start();
        t2.start();
    }
}
Output:5 10 15 20 25 100 200 300 400 500

使用匿名类的同步块的相同示例:

class Table{
    void printTable(int n){
        synchronized(this){
            //synchronized block for(int i=1;i<=5;i++){
                System.out.println(n*i);
                try{
                    Thread.sleep(400);
                }
                catch(Exception e){
                    System.out.println(e);
                }
            }
        }
    }
//end of the method}
public class TestSynchronizedBlock2{
    public static void main(String args[]){
        final Table obj = new Table();
        //only one objectThread t1=new Thread(){
            public void run(){
                obj.printTable(5);
            }
        }
        ;
        Thread t2=new Thread(){
            public void run(){
                obj.printTable(100);
            }
        }
        ;
        t1.start();
        t2.start();
    }
}
Output:5 10 15 20 25 100 200 300 400 500
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4