java 代码块同步,Java 同步代码块

Java 同步代码块

1 什么是Java同步代码块

同步代码块可用于对方法的任何特定资源执行同步。

假设您的方法中有50行代码,但是您只想同步5行,则可以使用synchronized代码块。

如果将方法的所有代码放在同步代码块中,它的效果与同步方法相同。

2 Java同步代码块的要点

同步代码块用于锁定任何共享资源的对象。

同步代码块的范围小于该方法。

3 Java同步代码块的语法

synchronized (object reference expression) {

//code block

}

4 Java同步代码块的例子1

让我们看一下同步代码块的简单示例。

package com.yiidian;

/**

* 一点教程网: http://www.yiidian.com

*/

/**

* Java同步代码块的例子

*/

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 Demo{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

}

}

输出结果为:

5

10

15

20

25

100

200

300

400

500

5 Java同步代码块的例子2

使用匿名类编写同步代码块程序:

package com.yiidian;

/**

* 一点教程网: http://www.yiidian.com

*/

/**

* Java同步代码块的例子

*/

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 Demo{

public static void main(String args[]){

final Table obj = new Table();//only one object

Thread t1=new Thread(){

public void run(){

obj.printTable(5);

}

};

Thread t2=new Thread(){

public void run(){

obj.printTable(100);

}

};

t1.start();

t2.start();

}

}

输出结果为:

5

10

15

20

25

100

200

300

400

500

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值