您的位置:首页 > 教育 > 锐评 > 使用多线程交替打印1-100

使用多线程交替打印1-100

2024/10/5 22:31:02 来源:https://blog.csdn.net/qq_41597232/article/details/142284862  浏览:    关键词:使用多线程交替打印1-100

多线程交替打印1-100

  • 使用ReentrantLock锁
  • 使用synchronized关键字
  • 使用条件锁

使用ReentrantLock锁

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ThreadExample extends Thread {private int id;private static int counter = 1;private static Lock lock = new ReentrantLock();public ThreadExample(int id) {this.id = id;}@Overridepublic void run() {while (counter < 100) {lock.lock();if (counter % 2 == id % 2) {System.out.println("thread " + id + ": " + counter);counter++;}lock.unlock();}}public static void main(String[] args) {Thread t1 = new ThreadExample(1);Thread t2 = new ThreadExample(2);t1.start();t2.start();}
}

使用synchronized关键字

public class ThreadExample extends Thread {private int id;private static int counter = 1;public ThreadExample(int id) {this.id = id;}@Overridepublic void run() {while (counter < 100) {synchronized (Thread.class) {if (counter % 2 == id % 2) {System.out.println("thread " + id + ": " + counter);counter++;}}}}public static void main(String[] args)  {Thread t1 = new ThreadExample(1);Thread t2 = new ThreadExample(2);t1.start();t2.start();}
}

使用条件锁

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;public class UseCondition {private static int num = 1;private ReentrantLock lock = new ReentrantLock();private Condition conditionA = lock.newCondition();private Condition conditionB = lock.newCondition();void print1() throws InterruptedException {lock.lock();while (num < 100) {if (num % 2 == 0) {conditionA.await();}System.out.println(Thread.currentThread().getName() + "  " + num++);conditionB.signal();}lock.unlock();}void print2() throws InterruptedException {lock.lock();while (num < 100) {if (num % 2 == 1) {conditionB.await();}System.out.println(Thread.currentThread().getName() + "  " + num++);conditionA.signal();}lock.unlock();}
}
public class ThreadExample implements Runnable {private int id;private static UseCondition useCondition = new UseCondition() ;public ThreadExample(int id){this.id = id;}@Overridepublic void run() {if (id == 0){try {useCondition.print1();} catch (InterruptedException e) {throw new RuntimeException(e);}}else{try {useCondition.print2();} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) {new Thread(new ThreadExample(0), "线程A").start();new Thread(new ThreadExample(1), "线程B").start();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com