多线程入门--synchronized介绍

来源:互联网 发布:旧时光影视论坛新域名 编辑:程序博客网 时间:2024/05/06 07:22

线程安全

非线程安全主要是指多个线程对同一个对象中 的同一个实例变量进行操作时会出现值被更改、值不同步的情况,进而影响程序的执行流 程。

/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
* {@code (null, target, name)}.
*
* @param target
* the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
*
* @param name
* the name of the new thread
*/
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}

实现多线程的资源共享:

public class Test {    public static void main(String[] args) {        Thread1 thread1 = new Thread1();        Thread a = new Thread(thread1, "A");        Thread b = new Thread(thread1, "B");        Thread c = new Thread(thread1, "C");        Thread d = new Thread(thread1, "D");        Thread e = new Thread(thread1, "E");        a.start();        b.start();        c.start();        d.start();        e.start();    }}

线程定义:

public class Thread1 extends Thread {    private int count=5;    @Override    public void run() {        super.run();        count--;        System.out.println(Thread.currentThread().getName() + " is running!");        System.out.println(Thread.currentThread().getName() + " count: " + count);    }}

虽然共享了资源,但是对资源count的访问是不同步的。

A is running!A count: 2C is running!B is running!C count: 0E is running!D is running!E count: 0B count: 0D count: 0

解决资源同步问题的一个方法是在更改资源的操作的方法前加上synchronized修饰符,表示对该方法的调用必须进行锁的争抢,只有一个线程能够进行方法的调用。

 @Override    synchronized public void run() {        super.run();        count--;        System.out.println(Thread.currentThread().getName() + " count: " + count);        System.out.println(Thread.currentThread().getName() + " is running!");    }
0 0