您的位置:首页 > 运维架构 > 网站架构

架构师之路--线程

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

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

package com.daniu56.thread;

@SuppressWarnings("unused")

public class Thread01 extends Thread{
priva
4000
te 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: