Welcome

首页 / 软件开发 / JAVA / Java多线程初学者指南(12):使用Synchronized块同步变量

Java多线程初学者指南(12):使用Synchronized块同步变量2010-02-01 BlogJava 银河使者我们可以通过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"))
030 method1();
031 }
032 public SyncThread(String methodType)
033 {
034 this.methodType = methodType;
035 }
036 public static void main(String[] args) throws Exception
037 {
038 SyncThread sample1 = new SyncThread("nonstatic");
039 SyncThread sample2 = new SyncThread("static");
040 sample1.start();
041 sample2.start();
042 }
043 }

运行结果如下:

method1
staticMethod1