Java线程同步

时间:2023-03-08 23:37:58
Java线程同步
package a.thread;

public class A {
private static int x = 0; public void run() {
// 同步代码块
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()
+ "=====;x=" + x);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
x++;
}
}
} // 同步方法
public synchronized void aa() {
for (int i = 0; i < 10; i++) {
System.out
.println(Thread.currentThread().getName() + "====;x=" + x);
x++;
}
}
}
package a.thread;

public class MainB {
public static void main(String[] args) {
final A a1 = new A();
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new Thread(new Runnable() { public void run() {
a1.aa();
a1.run();
}
});
threads[i].setName("线程" + i);
threads[i].start();
try {
threads[i].sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

同步方法---使用synchronized修饰的方法:

访问修饰符  synchronized [static] 数据返回类型 方法名() {

...........

}

防止多个线程同时访问这个类中的synchronized static 方法。static可以省略,它可以对类的所有对象实例起作用。

同步语句块---只对这个区块的资源实行互斥访问:

synchronized(共享对象名){

  被同步的代码段

}

1)它锁定的是共享对象名对应的当前对象。

2)线程中实现同步块一般是在run方法中添加。