可以在代码中加入synchronized代码块,也可以在方法的返回值前面加上synchronized声明。一把锁只能同时被一个线程获取,没有获得锁的线程只能等待。每个实例都对应有自己的一把锁,不同实例之间互不影响。synchronized修饰的方法,无论方法正常执行完毕还是抛出异常,都会释放锁。
import java.util.ArrayList;
public class myTest implements Runnable{
static myTest instance = new myTest();
public void test1() {
synchronized (this) {
System.out.println("test 1");
}
}
public synchronized void test2() {
System.out.println("This is "+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} System.out.println(Thread.currentThread().getName()+"运行结束!");
}
public static void main(String[] args) {
Thread t1 = new Thread(instance,"thread1");
Thread t2 = new Thread(instance,"thread2");
t2.start();
t1.start();
}
@Override
public void run() {
test2();
}
}