java的Synchronized的用法
public class Threads3 {
public static void main(String[] args) {
}
private static void demo5() {
Threads3 t3 = new Threads3();
new Thread(){
@Override
public void run() {
while(true){
t3.printer1();
}
}
}.start();
new Thread(){
@Override
public void run() {
while(true){
t3.printer2();
}
}
}.start();
}
public synchronized void printer1(){
System.out.print("k");
System.out.print("l");
System.out.print("z");
System.out.print("\r\n");
}
public static void printer2(){
System.out.print("范");
System.out.print("坚");
System.out.print("强");
System.out.print("\r\n");
}
private static void demo4() {
Threads3 t3 = new Threads3();
new Thread(new Runnable() {
@Override
public void run() {
t3.synchronized4();
}
}).start();
new Thread() {
public void run() {
t3.synchronized1();
};
}.start();
}
private static void demo3() {
Threads3 t3 = new Threads3();
new Thread(new Runnable() {
@Override
public void run() {
t3.synchronized1();
}
}).start();
new Thread() {
public void run() {
t3.stander();
};
}.start();
}
private static void demo2() {
Threads3 t3 = new Threads3();
Thread t1 = new Thread() {
public void run() {
t3.synchronized1();
};
};
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
t3.synchronized2();
}
});
t1.start();
t2.start();
}
private static void demo1() {
Threads3 t3 = new Threads3();
new Thread("klz") {
@Override
public void run() {
t3.synchronized1();
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
t3.synchronized1();
}
}).start();
}
public synchronized void synchronized1() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "aaa");
}
}
public synchronized void synchronized2() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "bbb");
}
}
public void stander() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "ccc");
}
}
public static synchronized void synchronized4() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "ddd");
}
}
public static void synchronized5() {
synchronized (Threads3.class) {
}
}
public static synchronized void synchronized6() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "eee");
}
}
}
class Singleton {
private Singleton() {
}
private static Singleton s = null;
private static Singleton getInstance() {
if (s == null) {
synchronized (Singleton.class) {
if (s == null) {
s = new Singleton();
}
}
}
return s;
}
}