synchronized void a(){
countDownLatch = new CountDownLatch(1);
// do someing
countDownLatch.await();
}
synchronized void b(){
countDownLatch.countDown();
}
byte[] mutex = new byte[0];
void a1(){
synchronized(mutex){
//dosomething
}
}
void b1(){
synchronized(mutex){
// dosomething
}
}
public class MultiThreadSync {
public synchronized void m1() throws InterruptedException{
System. out.println("m1 call" );
Thread. sleep(2000);
System. out.println("m1 call done" );
}
public void m2() throws InterruptedException{
synchronized (this ) {
System. out.println("m2 call" );
Thread. sleep(2000);
System. out.println("m2 call done" );
}
}
public static void main(String[] args) {
final MultiThreadSync thisObj = new MultiThreadSync();
Thread t1 = new Thread(){
@Override
public void run() {
try {
thisObj.m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread(){
@Override
public void run() {
try {
thisObj.m2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t2.start();
}
}
m1 call m1 call done m2 call m2 call done
void method(){
void synchronized method(){ synchronized(this){
// biz code // biz code
} ------>>> }
}
public class NoVisibility {
private static boolean ready = false;
private static int number = 0;
private static class ReaderThread extends Thread {
@Override
public void run() {
while (!ready) {
Thread.yield(); //交出CPU让其它线程工作
}
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
public class NoVisibility {
private static boolean ready = false;
private static int number = 0;
private static Object lock = new Object();
private static class ReaderThread extends Thread {
@Override
public void run() {
synchronized (lock) {
while (!ready) {
Thread.yield();
}
System.out.println(number);
}
}
}
public static void main(String[] args) {
synchronized (lock) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
}
//线程A,B共同访问的代码
Object lock = new Object();
int a=0;
int b=0;
int c=0;
//线程A,调用如下代码
synchronized(lock){
a=1; //1
b=2; //2
} //3
c=3; //4
//线程B,调用如下代码
synchronized(lock){ //5
System.out.println(a); //6
System.out.println(b); //7
System.out.println(c); //8
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有