Java多线程初学者指南(10):使用Synchronized关键字同步
要想解决“脏数据”的问题,最简单的方法就是使用synchronized关键字来使run方法同步,代码如下:
public synchronized void run(){ }
class Test { public synchronized void method() { } } public class Sync implements Runnable { private Test test; public void run() { test.method(); } public Sync(Test test) { this.test = test; } public static void main(String[] args) throws Exception { Test test1 = new Test(); Test test2 = new Test(); Sync sync1 = new Sync(test1); Sync sync2 = new Sync(test2); new Thread(sync1).start(); new Thread(sync2).start(); } }
Sync sync1 = new Sync(test1);
class Test { public static synchronized void method() { }}
Test test = new Test();
package test;// 线程安全的Singleton模式class Singleton{ private static Singleton sample; private Singleton() { } public static Singleton getInstance() { if (sample == null) { Thread.yield(); // 为了放大Singleton模式的线程不安全性 sample = new Singleton(); } return sample; }}public class MyThread extends Thread{ public void run() { Singleton singleton = Singleton.getInstance(); System.out.println(singleton.hashCode()); } public static void main(String[] args) { Thread threads[] = new Thread[5]; for (int i = 0; i < threads.length; i++) threads[i] = new MyThread(); for (int i = 0; i < threads.length; i++) threads[i].start(); }}
25358555263995547051261298553195383406
public static synchronized Singleton getInstance() { }
private static final Singleton sample = new Singleton();
class Parent{ public synchronized void method() { }}class Child extends Parent{ public synchronized void method() { }}
class Parent{ public synchronized void method() { }}class Child extends Parent{ public void method() { super.method(); }}
public synchronized void method();synchronized public void method();public static synchronized void method();public synchronized static void method();synchronized public static void method();
public void synchronized method();public static void synchronized method();
public synchronized int n = 0;public static synchronized int n = 0;
package test;public class MyThread1 extends Thread{ public String methodName; public static void method(String s) { System.out.println(s); while (true) ; } public synchronized void method1() { method("非静态的method1方法"); } public synchronized void method2() { method("非静态的method2方法"); } public static synchronized void method3() { method("静态的method3方法"); } public static synchronized void method4() { method("静态的method4方法"); } public void run() { try { getClass().getMethod(methodName).invoke(this); } catch (Exception e) { } } public static void main(String[] args) throws Exception { MyThread1 myThread1 = new MyThread1(); for (int i = 1; i <= 4; i++) { myThread1.methodName = "method" + String.valueOf(i); new Thread(myThread1).start(); sleep(100); } }}
非静态的method1方法静态的method3方法