synchronized关键字实现线程安全

/**
* Created by it on 2017/6/7.
*/
public class MyThread extends Thread {
private int val;
private Service service;
static RealExecu realExecu=new RealExecu();
public MyThread(int v) {
val = v;
}
public MyThread(Service service) {
this.service = service;
}
//这种做法是非线程安全的
public synchronized void print1(int v) throws InterruptedException {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
System.out.print(v);
}
}

public void print2(int v) throws InterruptedException {
//线程安全
synchronized (MyThread.class) {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
System.out.print(v);
}
}
}

public void run() {

try {
realExecu.print(val);
}

//print1(val);}
//print2(val);}

catch (InterruptedException ie){

}
}
}

/**
* Created by it on 2017/6/7.
*/
public class ThreadTest {
public static void main(String[] args) {
MyThread m1 = new MyThread(1);
MyThread m2 = new MyThread(2);

m1.start();
m2.start();
}
}
print1方法上加上synchronized,没有起同步作用,是因为该方法被不同实例调用,实现同步可以使用print2方法,在类实例上加锁;
print2方法等同于把方法放入一个类中,在mythread中定义静态类实例变量,以实现synchronized的同步作用
public class RealExecu {
public synchronized void print(int v) throws InterruptedException {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
System.out.print(v);
}
}
}
posted @ 2017-06-07 16:44  cindy_zhu  阅读(445)  评论(0编辑  收藏  举报