synchronized锁对象
1:定义线程,oneThread
public class OneThread implements Runnable { @Override public void run() { synchronized (this){ for (int i =0;i< 100;i++){ System.out.println(Thread.currentThread().getName()+"开始的编程号码为"+i); if (i == 10){ Thread.yield(); } } } } }
2:开始调用线程
public class TestThread { public static void main(String[] args) { Thread oneThread = new Thread(new OneThread(),"线程ONE"); Thread twoThread = new Thread(new OneThread(),"线程TWO"); oneThread.start(); twoThread.start(); } }
如此使用,synchronized锁会失效,因为new的是两个对象,synchronized获取的是两把不同的锁,所以会导致并发失效
3:修改synchronized是并发访问有效
public class OneThread implements Runnable { @Override public void run() { synchronized (OneThread.class){ for (int i =0;i< 100;i++){ System.out.println(Thread.currentThread().getName()+"开始的编程号码为"+i); if (i == 10){ Thread.yield(); } } } } }