线程的互斥操作(解决多线程共享数据问题)
1. 同步块(保证某一段代码在某一时刻只能有一个线程访问)
锁(java中任何对象都是一把锁,有且只有一把钥匙)
//同步函数,锁是this
public synchronized void f(){
System.out.print("hello world");
}
2. 同步函数
普通方法返回类型前加同步,锁就是当前对象
静态方法的锁就是当前对象的类类型
//这就是代码块 锁作为参数这里以this为例
synchronized(this){
System.out.print("hello world");
}
3.多线程共享数据
public class Test1 {
public static void main(String[] args) {
//创建一个对象
Output output = new Output();
//创建两个线程
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.print("hello");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.print("world");
}
}
}).start();
}
}
class Output{
public void print(String name){
/**
* 保证这段代码同时只有一个线程进来访问
* 一定要保证是同一个对象锁 这里用的是this(调用调用同步块的对象)
*/
synchronized (this) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
4.线程死锁
/**
* 第一个线程拿到a对象进入到第一个同步块
* 同时第二个线程拿到b对象第二个同步块
* 第一个线程等待第二个线程释放b
* 同时第二个线程等待第一个线程释放a
*/
synchronized(a){
synchronized(b){
System.out.print("hello");
}
}
synchronized(b){
synchronized(a){
System.out.print("hello");
}
}