一、使用两个线程循环打印出1~100
static class printNum{
public static void main(String[] args) {
TestThread testThread = new TestThread();
Thread A = new Thread(testThread,"线程1");
Thread B = new Thread(testThread,"线程2");
A.start();
B.start();
}
}
static class TestThread implements Runnable{
private int num = 0;
@Override
public void run() {
while (true){
synchronized (this){
notify();
if(num++ < 100){
System.out.println(Thread.currentThread().getName()+"输出了:"+num);
}else {
break;
}
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
二、使用三个线程循环打印出1~100
public class TestThread2 {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(new MyThread1(0));
Thread t2 = new Thread(new MyThread1(1));
Thread t3 = new Thread(new MyThread1(2));
t1.start();
t2.start();
t3.start();
}
static class MyThread1 implements Runnable {
private static Object lock = new Object();
private static int count = 0;
int no;
public MyThread1(int no) {
this.no = no;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
if (count >= 100) {
break;
}
if (count % 3 == this.no) {
count++;
System.out.println(this.no + "--->" + count);
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();
}
}
}
}
}
- 使用
Reentrantlock+Condition
实现(和wait/notifyAll
类似)
public class Test3 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread2(0));
Thread t2 = new Thread(new MyThread2(1));
Thread t3 = new Thread(new MyThread2(2));
t1.start();
t2.start();
t3.start();
}
static class MyThread2 implements Runnable{
private int no;
private static ReentrantLock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
private static int count;
public MyThread2(int no){
this.no = no;
}
@Override
public void run() {
lock.lock();
try {
while (true){
if (count>=100){
break;
}else {
if (count%3 == this.no){
count++;
System.out.println(this.no+"-->"+count);
}else {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
condition.signalAll();
}
} finally {
lock.unlock();
}
}
}
}