多线程入门--synchronized介绍

线程安全

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

/**
* 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: 2
C is running!
B is running!
C count: 0
E is running!
D is running!
E count: 0
B count: 0
D 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值