继承 Thread
class Thr extends Thread {
实现 runnable接口
class TT implements Runnable {
执行线程
public static void main(String[] args) {
new Thr().start();
new Thread(new TT(),"thread").start();
}
理解synchronized 的加锁原理.
package concurrent01.c000;
?
public class T {
?
private Integer count = 10;
?
public void run() {
for (int i = 0; i < 10; i++) {
count --;
System.out.println(Thread.currentThread().getName() +"thread name is"+count);
}
}
}
多个线程执行run()方法的时候,确保count的值每次只被一个线程修改.有四种方式
使用volatile关键字修饰
private volatile static Integer count = 10;
使用synchronized关键字,给代码上锁
package concurrent01.c000;
?
public class T {
?
private Integer count = 10;
?
private Object o = new Object();
?
public void t1() {
?
synchronized(o){
for (int i = 0; i < 10; i++) {
count --;
System.out.println(Thread.currentThread().getName() +"thread name is"+count);
}
}
}
}
可以将o替代成this.
public void t1() {
synchronized(this){
for (int i = 0; i < 10; i++) {
count --;
System.out.println(Thread.currentThread().getName() +"thread name is"+count);
}
}
也可以在方法上面加锁,这种方法和第三钟方式完全等效,代码在执行的时候,可以看成是一种方式
package concurrent01.c000;
?
public class T {
private volatile Integer count = 10;
public synchronized void t1() {
for (int i = 0; i < 10; i++) {
count --;
System.out.println(Thread.currentThread().getName() +"thread name is"+count);
}
}
}
synchronized 在执行一段代码的时候,需要给一个对象加锁.
执行过程
线程执行代码块,发现synchronized,查找锁对象
锁对象头空间有一个markdown标识,如果是00,说明这段代码还没有加锁,线程拿到代码的执行权,并给锁对象markdown标识设置为01,加锁.
其他线程执行到这里的时候,去查看锁对象的标识,发现是01,说明这段代码已经加锁,进入等待状态.
拿到锁的线程,执行完成之后,将锁对象的标识设置为00,即解锁
原文:https://www.cnblogs.com/regnol/p/13222396.html