多线程同步

多线程的同步依靠的是对象锁机制

多线程同步_第1张图片
线程状态

加错锁(this)但是每个线程都持有this对象的对象锁

class MyThread2 implements java.lang.Runnable
{
    private int threadId;

    public MyThread2(int id)
    {
        this.threadId = id;
    }
    @Override
    public synchronized void run() 
    {
        for (int i = 0; i < 100; ++i)
        {
            System.out.println("Thread ID: " + this.threadId + " : " + i);
        }
    }
}
public class Thread1
{
    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException
    {
        for (int i = 0; i < 10; ++i)
        {
            new Thread(new MyThread2(i)).start();
            Thread.sleep(1);
        }
    }
}

正确加锁外部创建共享资源(lock这个对象)的多线程

class MyThread implements java.lang.Runnable
{
    private int threadId;
    private Object lock;
    public MyThread(int id, Object obj)
    {
        this.threadId = id;
        this.lock = obj;
    }
    @Override
    public  void run() 
    {
        synchronized(lock)
        {
            for (int i = 0; i < 100; ++i)
            {
                System.out.println("Thread ID: " + this.threadId + " : " + i);
            }
        }
    }
}
public class ThreadDemo {
    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException
    {
        Object obj = new Object();
        for (int i = 0; i < 10; ++i)
        {
            new Thread(new MyThread(i, obj)).start();
            Thread.sleep(1);
        }
    }

}

你可能感兴趣的:(多线程同步)