多线程顺序打印0-100的两种方法
1.第一种方法主要是判断当前打印的数据是否符合,如果不符合让当前线程重新进入就绪状态,让线程调度器重新选择,直到符合为止。
package com.demo;
public class Test01 {
//打印的最大数值
public static final int LIMIT = 100;
public static int n = 1;
class MyThread implements Runnable{
public int mod ;
public MyThread(int mod) {
this.mod = mod;
}
@Override
public void run() {
while(n<LIMIT) {
if(n% mod == 0) {
System.out.println(n);
n++;
}else {
Thread.yield();
}
}
}
}
public static void main(String[] args) {
Test01 test = new Test01();
new Thread(test.new MyThread(1) ).start();
new Thread(test.new MyThread(2) ).start();
new Thread(test.new MyThread(3) ).start();
}
}
2.使用信号量互斥机制控制线程运行状态
package com.demo;
import java.util.concurrent.Semaphore;
public class Test02 {
//打印的最大数值
public static final int LIMIT = 100;
public static int n = 0;
//初始信号量为1
public static Semaphore semaphore1 = new Semaphore(1);
//初始信号量为0
public static Semaphore semaphore2 = new Semaphore(0);
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while(n<LIMIT) {
try {
//请求一个信号量,初始semaphore1有一可用个信号量,所以可以请求到
//请求semaphore1一个信号量后,semaphore1无可用的信号量
semaphore1.acquire();
System.out.println(n++);
//释放一个信号量
semaphore2.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(n<LIMIT) {
try {
//请求一个信号量,初始semaphore2没有可用个信号量,所以可以请求到
semaphore2.acquire();
System.out.println(n++);
//释放一个信号量
semaphore1.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}