多线程编程---两个线程交替打印1-100
方法1:使用synchronized同步代码块
首先要创建一个锁对象;再将两个线程的核心代码同步起来;
(本人并没有使用lambda表达式的方法创建线程)
(^ _ ^)
package org.example;
/**
* @author lhd
* @version 1.0
* @date 2024/5/26 22:11
*/
public class TwoThread {
static /*volatile*/ int cnt = 1;
static Object lock = new Object();
static class thread1 extends Thread{
@Override
public void run() {
while(true) {
synchronized (lock) {
if(cnt > 100) {
lock.notifyAll();
break;
}
System.out.println("线程A打印: " + cnt);
cnt++;
lock.notifyAll();
try{
lock.wait();
}catch (InterruptedException ex){}
}
}
}
}
static class thread2 extends Thread{
@Override
public void run() {
while(true) {
synchronized (lock) {
if(cnt > 100) break;
System.out.println("线程B打印: " + cnt);
cnt++;
lock.notifyAll();
try{
lock.wait();
}catch (InterruptedException ex){}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new thread1();
Thread t2 = new thread2();
t1.start();t2.start();
t1.join();t2.join();
}
}
- 对象监视器:每个 Java 对象都有一个隐含的监视器(或锁)。当线程进入同步块或方法时,它会获取对象的监视器。
- notifyAll() :主要作用是唤醒其他线程。唤醒所有等待在该对象监视器上的线程。
notifyAll() 的主要用途是在多线程环境中协调线程的执行。典型的应用场景是生产者-消费者模式或其他需要多个线程合作完成任务的情况。当一个线程完成了某个重要操作,或者满足了某些条件,可以调用 notifyAll() 方法来通知所有等待在该对象上的线程继续执行。
- wait():使当前线程进入等待状态,并释放对象的监视器;
- notify(): 唤醒一个等待在该对象监视器上的线程。
方法2 :使用conditiion控制两个线程
两个线程分别负责打印奇数和偶数。
通过 lock 和 condition 控制线程的执行顺序。
使用 while 循环和 condition.await() 方法来等待正确的打印时机。
package org.example;
import jdk.nashorn.internal.ir.ContinueNode;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author lhd
* @version 1.0
* @date 2024/5/26 22:31
*/
public class TwoThreadR {
static int cnt = 1;
static final Lock lock = new ReentrantLock();
static final Condition condition = lock.newCondition();
static boolean flag = true;
static class myRun1 implements Runnable{
private final int start;
public myRun1(int start){
this.start = start;
}
public void run(){
for (int i = start;i <=100;i += 2){
lock.lock();
try{
while((flag == true && i%2 == 0) || (flag == false && i%2 == 1)){
condition.await();
}
System.out.println("线程"+start+"打印: "+i);
flag = !flag;
condition.signalAll();
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new myRun1(1)) ;
Thread t2 = new Thread(new myRun1(2));
t1.start();
t2.start();
}
}