用wait和notify
/**
* 两个线程交替打印0~100的寄偶数,用wait和notify
*/
public class WaitNotifyPrintOddEvenWait {
private static int count = 0;
private static final Object lock = new Object();
public static void main(String[] args) {
new Thread(new TurningRunner(),"偶数").start();
new Thread(new TurningRunner(),"奇数").start();
}
//1.拿到锁,我们就打印
//2。一旦打印完唤醒其他线程就休眠
static class TurningRunner implements Runnable{
@Override
public void run() {
while (count <= 100) {
synchronized (lock){
System.out.println(Thread.currentThread().getName()+";"+ count++);
lock.notify();
if(count<=100){
try {
//如果任务没结束,唤醒其他线程,自己休眠
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
用synchroniser关键字实现
/**
* 两个线程交替打印0~100的即偶数,用synchroniser关键字实现
*/
public class WaitNotifyPrintOddEvenSyn {
private static int count;
private static final Object lock = new Object();
//新建两个线程
//第1个只处理偶数,第二个只处理奇数(用位运算)
//用synchronized来通讯,
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100){
synchronized (lock){
//count & 1 一个数字把它和1做位与的操作,1再二进制就是1,count转换位二进制,和1去与,就是取出count二进制的最低位,最低位是1代表奇数,0代表是偶数,比count%2 == 0 效率高
if((count & 1) == 0){
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
},"偶数").start();
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100){
synchronized (lock){
//count & 1 一个数字把它和1做位与的操作,1再二进制就是1,count转换位二进制,和1去与,就是取出count二进制的最低位,最低位是1代表奇数,0代表是偶数,比count%2 == 0 效率高
if((count & 1) == 1){
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
},"奇数").start();
}
}
上篇:手写一个设计者模式
下篇:Thread的常用方法sleep和join详解