synchronized详解
回想起来,代码中一直用synchronized了,但是好像对它理解不到位,今天抓点时间复习一下。写了几个代码例子说明一下。
结构简述:
定义了一个资源PrintDemo,一个线程类ThreadDemo,一个测试类TestThread,在测试类中创建两个线程对象,两个线程对象都通过run方法访问资源PrintDemo.printCount方法
第一种场景:不对资源加锁
package com.yy.test;
/**
* Created by skyler on 2017/2/17.
*/
class PrintDemo {
public void printCount() {
try {
for(int i = 10; i > 0; i--) {
System.out.println("Counter --- " + i );
}
}catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
PD.printCount();
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
TestThread tt = new TestThread();
tt.test1();
}
public void test1() {
PrintDemo2 PD = new PrintDemo2();
ThreadDemo2 T1 = new ThreadDemo2( "Thread - 1 ", PD );
ThreadDemo2 T2 = new ThreadDemo2( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
}catch( Exception e) {
System.out.println("Interrupted");
}
}
}
运行结果:
Starting Thread - 1
Starting Thread - 2
Counter --- 10
Counter --- 10
Counter --- 9
Counter --- 9
Counter --- 8
Counter --- 8
Counter --- 7
Counter --- 6
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter -