synchronized关键字用于对代码段添加线程锁。
class Worker{
static int i = 0;
public void do_add() {
synchronized (this) {
i++;
System.out.println("i = " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread{
private Worker worker;
public MyThread(Worker w){
this.worker = w;
}
@Override
public void run(){
worker.do_add();
}
}
public class ThreadTest{
public static void main(String [] args) {
int ThreadNum = 10;
for(int j=0; j<ThreadNum; j++) {
Worker worker = new Worker();
Thread t = new MyThread(worker);
t.start();
}
}
}
上面程序,在main()中,每次new一个Worker对象,每个Mythread持有不同的Worker对象。所以,syncronized(this)的代码段不会被锁住,应该用synchronized (Worker.class)锁。或者在main中,将worker的初始化移到for外,这样syncronized(this)能够锁住代码段,因为10个线程共享一个worker。
用Runnable方式实现同样功能
class MyThread implements Runnable{
int i = 0;
public void run(){
synchronized (this) {
i++;
System.out.println("iii = " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest2{
public static void main(String [] args) {
int ThreadNum = 10;
MyThread mt = new MyThread();
for(int j=0; j<ThreadNum; j++) {
Thread t = new Thread(mt);
t.start();
}
}
}