线程交替打印奇偶数 Linux c,多线程交替打印奇偶数

LockSupport

原理

1460000039855865贴一个之前的笔记,字迹比较潦草zz 有空的时候这里会补上说明

实现1import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.LockSupport;

class Main{

static Thread a = null, b=null;

public static void main(String[] args){

a = new Thread(new Runnable() {

@Override

public void run() {

for(int i = 1;i<=99;i+=2){

System.out.println(i);

LockSupport.unpark(b);

LockSupport.park();

}

}

});

b = new Thread(new Runnable() {

@Override

public void run() {

for(int i = 2;i<=100;i+=2){

LockSupport.park();

System.out.println(i);

LockSupport.unpark(a);

}

}

});

a.start();

b.start();

}

}

实现2import java.util.concurrent.atomic.AtomicInteger;

import java.util.concurrent.locks.LockSupport;

public class Main {

static AtomicInteger num = new AtomicInteger(1);

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

Print p1 = new Print();

Print p2 = new Print();

Thread t1 = new Thread(p1); //t1对应p1任务 但p1任务的线程挂在t2上方便t1唤醒它

Thread t2 = new Thread(p2);

t1.setName("thread-cc-1");

t2.setName("thread-cc-2");

p1.setT(t2);//给p1的Thread设置为t2方便t1唤醒它

p2.setT(t1);

t1.start();

t2.start();

// 唤醒线程t1打印奇数,线程1打印奇数,线程2打印偶数

LockSupport.unpark(t1);

}

static class Print implements Runnable {

private volatile Thread t;

@Override

public void run() {

while (true) {

// 进入之后立即阻塞

LockSupport.park();

if (num.get() > 100) {

LockSupport.unpark(t);

return;

}

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

// 这里的t实际上是与currentThread不同的另一个线程

// 因此实现了 奇数唤醒偶数线程,偶数唤醒奇数线程

LockSupport.unpark(t);

}

}

public void setT(Thread t) {

this.t = t;

}

}

}

点评:可拓展性实现2相对较差一些(实现3个线程交替打印etc)

Synchronized + wait/notify实现public class Main{

public static void main(String[] args){

MyPrint print = new MyPrint();

Thread thread1 = new Thread(print,"A");

Thread thread2 = new Thread(print,"B");

thread1.start();

thread2.start();

}

}

class MyPrint implements Runnable{

int i = 1;

@Override

public void run() {

while (true){

synchronized (this){

this.notify();//在这里唤醒的目的是为保证拿到锁的线程只有一个

// 不会立即释放锁 退出代码块才会释放锁

if (i <= 100){

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

}else {

return;

}

try {

this.wait();//打印过数据的线程等待 必须等到没打印过数字的拿到锁了才能唤醒

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值