两个线程交替打印0~100的奇偶数:
偶线程:0
奇线程:1
偶线程:2
奇线程:3
......
public class Test {
public static void main(String[] args) {
// 创建两条线程,奇数线程打印奇数,偶数线程打印偶数
Thread thread1 = new Thread(new ThreadTask(), "偶数线程");
Thread thread2 = new Thread(new ThreadTask(), "奇数线程");
thread1.start();
thread2.start();
}
static class ThreadTask implements Runnable {
// 静态变量:创建对象时不会重置值
static int value = 0;
@Override
public void run() {
while(value < 100){
// ThreadTask.class加锁后,在释放锁之前不能被其它线程使用;
synchronized (ThreadTask.class) {
System.out.println(Thread.currentThread().getName() + ":" + value ++);
//先唤醒,再让出锁
ThreadTask.class.notify();
try {
//在执行wait()方法后会释放锁,进入等待状态。
ThreadTask.class.wait();
} catch (InterruptedException e) {
System.out.println(666);
}
}
}
}
}
}
通过N个线程顺序循环打印从0至100,如给定N=3则输出:
thread0: 0
thread1: 1
thread2: 2
thread0: 3
thread1: 4
.....
public class Test {
// 创建N条线程,循环打印0-100
public static void main(String[] args) {
int N = 4;
for (int i = 0; i < N; i++) {
Thread thread = new Thread(new ThreadTask(i, N), "thread" + i);
thread.start();
}
}
static class ThreadTask implements Runnable {
static int value = 0;
private int threadNo;
private int maxNo;
public ThreadTask(int i, int N) {
this.threadNo = i;
this.maxNo = N;
}
@Override
public void run() {
while(value < 100){
// 加锁后,在释放锁之前不能被其它线程使用;在执行wait()方法后会释放锁,进入等待状态。
synchronized (ThreadTask.class) {
//当线程执行的顺序不对时,线程进入等待状态
while ((value - threadNo) % maxNo != 0) {
try {
ThreadTask.class.wait();
} catch (InterruptedException e) {
System.out.println(666);
}
}
//否则打印数字并唤醒大家,然后进入等待状态
System.out.println(Thread.currentThread().getName() + ":" + value ++);
ThreadTask.class.notifyAll();
try {
ThreadTask.class.wait();
} catch (InterruptedException e) {
System.out.println(666);
}
}
}
}
}
}
notifyAll()方法唤醒所有线程,然后大家会去抢夺锁,抢到的线程再判断应不应该是这个线程,是的话则执行程序,不是就继续等待让出锁,直到正确的线程执行完程序后再唤醒大家,自己进入等待状态。
notify()、notifyAll()、wait()方法必须在synchronized关键字内使用