j
public class Thread1 implements Runnable {
public void print(Object lockSingal) {
synchronized (lockSingal) {
int i = 0;
while (true) {
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread_11111111 print i="+i++);
}
}
}
@Override
public void run() {
this.print(TestSynchronized.class);
}
}
——————————————————————————
public class Thread2 implements Runnable{
public void print(Object lockSingal) {
synchronized (lockSingal) {
int j = 0;
while (true) {
try {
Thread.sleep(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread_2 print j="+j++);
}
}
}
@Override
public void run() {
this.print(TestSynchronized.class);
}
}
————————————————————
public class TestSynchronized {
public static Object lockSignal = new Object();
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
new Thread(thread1).start();
new Thread(thread2).start();
}
}
运行结果先取到同一个类级别锁的线程一直运行,另一个线程得不到锁了,因为先取到锁的本例中是个永远的循环不会释放锁
——————————————————————————
第二种类级别同步锁的写法:
public class TestSynchronized {
public static Object lockSignal = new Object();
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
new Thread(thread1).start();
new Thread(thread2).start();
}
}
public class Thread1 implements Runnable {
public void print(Object lockSingal) {
synchronized (lockSingal) {
int i = 0;
while (true) {
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread_11111111 print i="+i++);
}
}
}
@Override
public void run() {
this.print(TestSynchronized.lockSignal);
}
}
public class Thread2 implements Runnable{
public void print(Object lockSingal) {
synchronized (lockSingal) {
int j = 0;
while (true) {
try {
Thread.sleep(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread_2 print j="+j++);
}
}
}
@Override
public void run() {
this.print(TestSynchronized.lockSignal);
}
}
运行效果是一样的



