如何找出线程安全问题:
1.明确那些代码块是多线程运行代码
2.明确共享数据
3.明确多线程运行代码中哪些语句是操作共享数据的
同步函数示例:
class Save{ private int sum; public synchronized void add(int n){ sum+=n; System.out.println("sum="+sum); } } class Cus implements Runnable{ private Save b=new Save(); public void run(){ for(int x=0;x<3;x++){ b.add(100); } } } class Bank{ public static void main(String[] args){ Cus c=new Cus(); Thread th1=new Thread(c); Thread th2=new Thread(c); th1.start(); th2.start(); } }
本文介绍了一种检查线程安全性的方法,包括识别多线程运行的代码块、确定共享数据及操作这些数据的语句。并通过一个示例程序演示了如何使用`synchronized`关键字来确保方法的线程安全性。
791

被折叠的 条评论
为什么被折叠?



