1.多线程依次打印ABC - synchronized
package com.self.thread.moreThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadTest {
static int state = 0;
private static Object 0 = new Object();
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
service.execute(new ThreadA());
service.execute(new ThreadB());
service.execute(new ThreadC());
service.shutdown();
}
public static class ThreadA implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (0) {
while (state % 3 != 0) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--------第" + (i + 1) + "轮打印--------");
System.out.println("A");
state++;
o.notifyAll();
}
}
}
}
public static class ThreadB implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (o) {
while (state % 3 != 1) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
state++;
o.notifyAll();
}
}
}
}
public static class ThreadC implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (o) {
while (state % 3 != 2) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
state++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
o.notifyAll();
}
}
}
}
}
2.多线程依次打印ABC - lock
package com.self.thread.moreThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest2 {
static int state = 0;
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
service.submit(new ThreadA());
service.submit(new ThreadB());
service.submit(new ThreadC());
service.shutdown();
}
public static class ThreadA implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; ) {
lock.lock();
if (state % 3 == 0) {
System.out.println("--------第" + (i + 1) + "轮打印--------");
System.out.println("A");
state++;
i++;
}
lock.unlock();
}
}
}
public static class ThreadB implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; ) {
lock.lock();
if (state % 3 == 1) {
System.out.println("B");
state++;
i++;
}
lock.unlock();
}
}
}
public static class ThreadC implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; ) {
lock.lock();
if (state % 3 == 2) {
System.out.println("C");
state++;
i++;
}
lock.unlock();
}
}
}
}