第一种方式:
package mianshi.Thread;
/**
* 2个线程 循环打印 abab
* 实现1:
* note: 2个线程操作 Work类, work类里面 实现互斥的 2个打印方法 A B。 2个线程各自调用A,B
*/
public class ThreadA {
public static void main(String[] args) {
Work t = new Work();
new Thread(new Runnable() {
@Override
public void run() {
t.printA();
//t.printD();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.printB();
//t.printC();
}
}).start();
}
}
package mianshi.Thread;
/**
* note: work类里面 实现互斥的 2个打印方法 A B。 2个线程各自调用A,B
*/
public class Work{
volatile static boolean flag = true;
public synchronized void printA() {
System.out.println("AAAA");
while (true) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a");
flag = false;
this.notifyAll();
}
}
public synchronized void printB() {
System.out.println("bbbb");
while (true) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b");
flag = true;
this.notifyAll();
}
}
public void printC() {
System.out.println("c");
}
public synchronized void printD() {
System.out.println("d");
}
}
第二种方式:
1 package mianshi.Thread;
2
3 /**
4 * 2个线程 循环打印 abab
5 * 实现2:
6 * note: 2个线程操作一个对象,主要是利用这个对象的 wait,notify,synchronize,然后 2个线程各自调用A,B
7 */
8 public class PrintAB {
9 static boolean flag = true;
10
11 public static void main(String[] args) {
12 PrintAB t = new PrintAB();
13
14 new Thread(new Runnable() {
15 @Override
16 public void run() {
17 synchronized (t) {
18 while (true) {
19 if (!flag) {
20 try {
21 t.wait();
22 } catch (InterruptedException e) {
23 e.printStackTrace();
24 } finally {
25 }
26 }
27 System.out.println("a");
28 flag = false;
29 t.notifyAll();
30 }
31 }
32 }
33 }).start();
34
35 new Thread(new Runnable() {
36 @Override
37 public void run() {
38 synchronized (t) {
39 while (true) {
40 if (flag) {
41 try {
42 t.wait();
43 } catch (InterruptedException e) {
44 e.printStackTrace();
45 } finally {
46 }
47 }
48 System.out.println("b");
49 flag = true;
50 t.notifyAll();
51 }
52 }
53 }
54 }).start();
55 }
56 }