Lock
程序员文章站
2022-04-19 09:53:20
...
Lock
一、
1.
2.
一、
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 ; } } } } }
上一篇: Python基础学习之列表的介绍
推荐阅读
-
ThinkPad笔记本电脑的Scroll Lock功能如何开启或关闭
-
关键字Lock的简单小例子
-
mysql报错:Deadlock found when trying to get lock; try restarting transaction的解决方法
-
mysql 开发进阶篇系列 20 MySQL Server(innodb_lock_wait_timeout,innodb_support_xa,innodb _log_*)
-
MySQL表结构变更你不可不知的Metadata Lock详解
-
同步锁Lock
-
Python多进程同步Lock、Semaphore、Event实例
-
AQS 框架之 Lock 接口
-
C# Lock锁(个人随记)
-
初识Lock与AbstractQueuedSynchronizer(AQS)