1.两个线程轮番打印奇数和偶数1-100
方法一:使用单线程池来实现
public class 两个线程打印奇数偶数 {
public static void main(String[] args) {
ExecutorService pool=Executors.newSingleThreadExecutor();
AtomicInteger a=new AtomicInteger(0);
AtomicInteger b=new AtomicInteger(1);
for(int i=0;i<50;i++) {
pool.execute(()->System.out.println(a.getAndAdd(2)+1));
pool.execute(()->System.out.println(b.getAndAdd(2)+1));
}
pool.shutdown();
}
}
方法二:使用ReentrantLock()来控制
public class 线程创建 {
private static ReentrantLock lock = new ReentrantLock();
private static int state= 0;
public static void main(String[] args) {
new Jithread().start();
new Outhread().start();
}
static class Jithread extends Thread{
@Override
public void run() {
for (int i = 0; i<50;) {
try {
lock.lock();
while (state%2==0){
System.out.print(state+" ");
state++;
i++;
}
}finally {
lock.unlock();
}
}
}
}
static class Outhread extends Thread{
@Override
public void run() {
for (int i = 0; i<50;) {
try {
lock.lock();
while (state%2==1){
System.out.print(state+" ");
state++;
i++;
}
}finally {
lock.unlock();
}
}
}
}
}
2.三个线程轮番输出10次ABC
线程池方法
public class 三个线程打印ABC{
public static void main(String[] args) {
ExecutorService pool=Executors.newSingleThreadExecutor();
for(int i=0;i<10;i++) {
pool.execute(()->System.out.print("A"));
pool.execute(()->System.out.print("B"));
pool.execute(()->System.out.print("C"));
pool.execute(()->System.out.println());
}
pool.shutdown();
}
}
锁方法
public class 三个线程打印ABC {
static ReentrantLock lock=new ReentrantLock();
static int state=0;
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
static class ThreadA extends Thread{
@Override
public void run() {
int sum=0;
for(int i=0;i<10;) {
try {
lock.lock();
while(state%3==0) {
System.out.print("A");
i++;
state++;
}
}finally {
lock.unlock();
System.out.println(sum++);
}
}
}
}
static class ThreadB extends Thread{
public void run() {
for(int i=0;i<10;) {
try {
lock.lock();
while(state%3==1) {
System.out.print("B");
i++;
state++;
}
}finally {
lock.unlock();
}
}
}
}
static class ThreadC extends Thread{
public void run() {
for(int i=0;i<10;) {
try {
lock.lock();
while(state%3==2) {
System.out.print("C");
i++;
state++;
}
}finally {
lock.unlock();
}
}
}
}
}