Last active
March 20, 2018 06:57
-
-
Save john990/3984b2a7db9cebf9bbc1097b065dea77 to your computer and use it in GitHub Desktop.
线程间通信,wait、notify的使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.java.test.thread; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* Created by John on 18/3/19. | |
* 使用三个线程使得ABC 循环输出十次 | |
*/ | |
public class PrintABC { | |
private static volatile String NEXT_TEXT = "C"; | |
private static AtomicInteger COUNT = new AtomicInteger(0); | |
private static final Object lock = new Object(); | |
public static void main(String[] args) { | |
new Thread(new PrintTask("A")).start(); | |
new Thread(new PrintTask("B")).start(); | |
new Thread(new PrintTask("C")).start(); | |
} | |
private static String getNextText() { | |
if ("A".equals(NEXT_TEXT)) { | |
return "B"; | |
} | |
if ("B".equals(NEXT_TEXT)) { | |
return "C"; | |
} | |
if ("C".equals(NEXT_TEXT)) { | |
return "A"; | |
} | |
return null; | |
} | |
private static class PrintTask implements Runnable { | |
private String text; | |
private PrintTask(String text) { | |
this.text = text; | |
} | |
@Override | |
public void run() { | |
print(); | |
} | |
private void print() { | |
synchronized (lock) { | |
for (; COUNT.get() < 10; ) { | |
String nextText = getNextText(); | |
if (text.equals(nextText)) { | |
if (text.equals("A")) { | |
System.out.print(COUNT.get() + ":"); | |
} | |
System.out.print(text); | |
if (text.equals("C")) { | |
System.out.print("\n"); | |
COUNT.incrementAndGet(); | |
} | |
NEXT_TEXT = text; | |
lock.notifyAll(); | |
} | |
if (COUNT.get() >= 10) { | |
return; | |
} | |
try { | |
lock.wait(10); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment