欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lock

程序员文章站 2022-03-09 18:53:32
...
Lock

一、

1.



public class ThreadSynchronizedDemo {

public static String name = "zhang" ;
public static Integer age = 25 ;

/**
* @param args
*/
public static void main(String[] args) {

/**
* 预期输出:
* zhang : 25
* li : 24
* 实际输出:
* 各种组合,
* 原因:
* 线程的执行时无序的,谁先执行取决于谁先占用CPU
* 即,可能出现 先printDemo 打印一般的时候,ChangeDemo 生效修改了 其他的值
*/
new Thread(new PrintDemo()).start();
new Thread(new ChangeDemo()).start();
}

}

class PrintDemo implements Runnable{

@Override
public void run() {
while(true){
System.out.println("name:"+ThreadSynchronizedDemo.name+" age:"+ThreadSynchronizedDemo.age);
}
}

}

class ChangeDemo implements Runnable{

@Override
public void run() {
while(true){
if("zhang".equals(ThreadSynchronizedDemo.name)){
ThreadSynchronizedDemo.name = "li";
ThreadSynchronizedDemo.age = 24 ;
}else{
ThreadSynchronizedDemo.name = "zhang" ;
ThreadSynchronizedDemo.age = 25 ;
}
}
}

}


2.


public class ThreadSynchronizedDemo {

public static String name = "zhang" ;
public static Integer age = 25 ;

public static void main(String[] args) {

/**
* Synchronized:
* 代码块锁机制
* 1.锁加在哪:欲同步的位置
* 2.锁对象:
* 共享的资源/类的字节码 class / 某一不变的对象 private static final Object object
*/
new Thread(new PrintDemo()).start();
new Thread(new ChangeDemo()).start();
}

}

class PrintDemo implements Runnable{

@Override
public void run() {
while(true){
synchronized (ThreadSynchronizedDemo.class) {
System.out.println("name:"+ThreadSynchronizedDemo.name+" age:"+ThreadSynchronizedDemo.age);
}
}
}

}

class ChangeDemo implements Runnable{

@Override
public void run() {
synchronized (ThreadSynchronizedDemo.class) {
while(true){
if("zhang".equals(ThreadSynchronizedDemo.name)){
ThreadSynchronizedDemo.name = "li";
ThreadSynchronizedDemo.age = 24 ;
}else{
ThreadSynchronizedDemo.name = "zhang" ;
ThreadSynchronizedDemo.age = 25 ;
}
}
}
}

}
相关标签: lock