java两线程交替打印1 0_用代码实现两个线程交替打印0-100的奇偶数

趣学python 100例程序设计编程算法

58.9元

包邮

(需用券)

去购买 >

java两线程交替打印1 0_用代码实现两个线程交替打印0-100的奇偶数_第1张图片

用synchronized关键字实现

/**

用代码实现两个线程交替打印0-100的奇偶数,用synchronized关键字实现

*/

public class WaitNotifyPrintOddEvenSyn {

//2个线程

//一个处理偶数,一个处理奇数(使用位运算)

//用synchronized来通信

private static int count;

private static final Object lock =new Object();

public static void main(String[] args) {

new Thread(new Runnable() {

@Override

public void run() {

while (count<100){

synchronized (lock){

//使用位运算 0代表偶数,1代表奇数

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){

//使用位运算 0代表偶数,1代表奇数

if((count & 1) == 1){

System.out.println(Thread.currentThread().getName()+":"+count++);

}

}

}

}

},"奇数").start();

}

}

使用wait/notify

/**

两个线程交替打印0~100奇偶数,用wait/notify

*/

public class WaitNotifyPrintOddEveWait {

//1.拿到锁就打印

//2.打印完,唤醒其他线程,就休眠

private static int count =0;

private static final Object lock = new Object();

public static void main(String[] args) throws InterruptedException {

Thread thread = new Thread(new TurningRunner(),"偶数");

Thread thread1 = new Thread(new TurningRunner(),"奇数");

thread.start();

Thread.sleep(10);//稍作休眠,防止线程启动的顺序不一致

thread1.start();

}

static class TurningRunner implements Runnable{

@Override

public void run() {

while (count<=100){

synchronized (lock){

//拿到锁就打印

System.out.println(Thread.currentThread().getName()+":"+count++);

//只有两个线程,所以唤醒使用notify和notifAll 一样,唤醒那个睡眠的锁

lock.notify();

if(count<=100){

try {

//如果任务还没结束,就让出当前的锁,让自己去休眠

lock.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

}

}

java 11官方入门(第8版)教材

79.84元

包邮

(需用券)

去购买 >

f0f3f55624fb396b1764d42d6df88864.png

你可能感兴趣的:(java两线程交替打印1,0)