synchronized

synchronized关键字定义同步代码块活方法,进入同步代码块的线程获得该对象的锁。锁没有释放,其他线程阻塞,锁释放,其他线程争锁。

实例锁:synchronized修饰非静态方法,线程获得普通对象的锁。

类锁:synchronized修饰静态方法,线程获得Class对象的锁。

class MyThread implements Runnable {
    synchronized public void run() {
        int i = 0;
        while(i < 6) {
            System.out.println(Thread.currentThread() + " a = " + i);
            i++;
            Thread.yield();
        }
    }
}
public class Demo1 {

    public static void main(String[] args) throws Exception {
        MyThread m = new MyThread();
        Thread t1 = new Thread(m,"t1");
        Thread t2 = new Thread(m,"t2");
        t1.start();
        t2.start();
        m.run();
    }

}

从这里可以看出来,线程只负责驱动任务,它并不关心任务是什么,即使一样的任务对象它也不在意。

posted @ 2020-03-15 22:20  卑微芒果  Views(130)  Comments(0Edit  收藏  举报