2014年百度seo网站排名的详细优化因素统计,国际学校网站如何建设,wordpress 邮件找客户,无锡建设工程项目代码申请网站synchronized的基本使用 可以在代码中加入synchronized代码块#xff0c;也可以在方法的返回值前面加上synchronized声明。一把锁只能同时被一个线程获取#xff0c;没有获得锁的线程只能等待。每个实例都对应有自己的一把锁#xff0c;不同实例之间互不影响。synchronized修…synchronized的基本使用 可以在代码中加入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();}Overridepublic void run() {test2();}
}