架构师之路--线程

线程安全概念:当多个线程访问同一个类时,这个类始终能保持正确的行为,那么这个类(对象或方法)就是线程安全的。

synchronized:可以在任意对象或方法上加锁,加锁的这段代码被称为“互斥区”或“临界区”。

package com.daniu56.thread;
@SuppressWarnings("unused")
public class Thread01 extends Thread{
private int count = 0;
public void run(){
count++;
System.out.println(this.currentThread().getName() +"===="+ count);
}

public static void main(String[] args) {
Thread01 myThread = new Thread01();
Thread thread01=new Thread(myThread,"t1");
Thread thread02=new Thread(myThread,"t2");
Thread thread03=new Thread(myThread,"t3");
Thread thread04=new Thread(myThread,"t4");
Thread thread05=new Thread(myThread,"t5");

thread01.start();
thread02.start();
thread03.start();
thread04.start();
thread05.start();
}
}

没有加“synchronized”之前,运行结果如下

t1====1
t2====3
t3====3
t4====3
t5====5


加入之后

变为

t1====1
t2====2
t3====3
t4====4
t5====5


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值