我们可以通过synchronized块来同步特定的静态或非静态方法。要想实现这种需求必须为这些特性的方法定义一个类变量,然后将这些方法的代码用synchronized块括起来,并将这个类变量作为参数传入synchronized块。下面的代码演示了如何同步特定的类方法:
001
package
mythread;
002
003 public class SyncThread extends Thread
004 {
005 private static String sync = "" ;
006 private String methodType = "" ;
007
008 private static void method(String s)
009 {
010 synchronized (sync)
011 {
012
sync
=
s;
013 System.out.println(s);
014 while ( true );
015 }
016 }
017 public void method1()
018 {
019 method( " method1 " );
020 }
021 public static void staticMethod1()
022 {
023 method( " staticMethod1 " );
024 }
025 public void run()
026 {
027 if (methodType.equals( " static " ))
028 staticMethod1();
029 else if (methodType.equals( " nonstatic "
002
003 public class SyncThread extends Thread
004 {
005 private static String sync = "" ;
006 private String methodType = "" ;
007
008 private static void method(String s)
009 {
010 synchronized (sync)
011 {
013 System.out.println(s);
014 while ( true );
015 }
016 }
017 public void method1()
018 {
019 method( " method1 " );
020 }
021 public static void staticMethod1()
022 {
023 method( " staticMethod1 " );
024 }
025 public void run()
026 {
027 if (methodType.equals( " static " ))
028 staticMethod1();
029 else if (methodType.equals( " nonstatic "
- <script type="text/java script">BAIDU_CLB_fillSlot("771048");
- 点击复制链接 与好友分享! 回本站首页 <script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732">
<script type="text/java script" id="bdshell_js">
<script type="text/java script">
var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}};
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)