摘要:2个线程各自调用A,B*/publicclassWork{volatilestaticbooleanflag=true;publicsynchronizedvoidprintA(){System.out.println;while{if(!
第一种方式:
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 classWork{
volatile static boolean flag = true;
public synchronized voidprintA() {
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 voidprintB() {
System.out.println("bbbb");
while (true) {
if(flag) {
try{
wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b");
flag = true;
this.notifyAll();
}
}
public voidprintC() {
System.out.println("c");
}
public synchronized voidprintD() {
System.out.println("d");
}
}
第二种方式:
1 packagemianshi.Thread;
2
3 /**
4 * 2个线程 循环打印 abab
5 * 实现2:
6 * note: 2个线程操作一个对象,主要是利用这个对象的 wait,notify,synchronize,然后 2个线程各自调用A,B
7 */
8 public classPrintAB {
9 static boolean flag = true;
10
11 public static voidmain(String[] args) {
12 PrintAB t = newPrintAB();
13
14 new Thread(newRunnable() {
15 @Override
16 public voidrun() {
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(newRunnable() {
36 @Override
37 public voidrun() {
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 }