public class ThreadTest {
static int a = 0;
public ThreadTest(int a){
this.a = a;
}
public synchronized void printOne(){
try {
while (a%3!=1){
this.wait();
}
System.out.println(Thread.currentThread().getName()+"---" + a++);
Thread.sleep(1000);
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printTwo(){
try {
while (a%3!=2){
this.wait();
}
System.out.println(Thread.currentThread().getName()+"---" + a++);
Thread.sleep(1000);
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printThree(){
try {
while (a%3!=0){
this.wait();
}
System.out.println(Thread.currentThread().getName()+"---" + a++);
Thread.sleep(100);
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ThreadTest a = new ThreadTest(0);
Thread threadOne = new Thread(new PrintOne(a));
Thread threadTwo = new Thread(new PrintTwo(a));
Thread threadThree = new Thread(new PrintThree(a));
threadOne.setName("one");
threadTwo.setName("two");
threadThree.setName("three");
threadOne.start();
threadTwo.start();
threadThree.start();
}
}
class PrintOne implements Runnable{
private ThreadTest threadTest;
public PrintOne(ThreadTest threadTest){
this.threadTest = threadTest;
}
@Override
public void run() {
while (true){
threadTest.printOne();
}
}
}
class PrintTwo implements Runnable{
private ThreadTest threadTest;
public PrintTwo(ThreadTest threadTest){
this.threadTest = threadTest;
}
@Override
public void run() {
while (true){
threadTest.printTwo();
}
}
}
class PrintThree implements Runnable{
private ThreadTest threadTest;
public PrintThree(ThreadTest threadTest){
this.threadTest = threadTest;
}
@Override
public void run() {
while (true){
threadTest.printThree();
}
}
}