做个ppt模板网站开发,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();}
}