本文共 3357 字,大约阅读时间需要 11 分钟。
本题目:两个线程需要轮流打印两个数,涉及了线程间的通信及wait()和notify()的应用。
解题思路:用synchronized来锁住对象,wait和notify进行线程间的通信。
先创建一个待打印的类
//新建一个类,用于打印这个类class Num{ int i = 1; // 标识 boolean flag = false; public Num() { }}
再创建一个奇数线程
// 奇数线程class PrintOdd implements Runnable{ Num num; public PrintOdd(Num num) { this.num = num; } @Override public void run() { while(num.i<=100) { // 锁住该对象 synchronized (num) { // 判断当前线程是否执行 if(num.flag) { try { num.wait(); }catch(InterruptedException e) { System.out.println(e.getMessage()); } }else { System.out.println(Thread.currentThread().getName()+num.i); num.i++; num.flag = true; // 唤醒 num.notify(); } } } }}
之后创建一个偶数线程
// 偶数线程class PrintEven implements Runnable{ Num num; public PrintEven(Num num) { this.num = num; } @Override public void run() { // TODO Auto-generated method stub while(num.i<=100) { // 锁住这个对象 synchronized (num) { if(!num.flag) { try { num.wait(); }catch (InterruptedException e) { // TODO: handle exception System.out.print(e.getMessage()); } }else { System.out.println(Thread.currentThread().getName()+num.i); num.i++; num.flag = false; num.notify(); } } } }}
最后主函数中测试
public class Print_Odd_Even { public static void main(String[] args) { Num num = new Num(); PrintOdd printOdd = new PrintOdd(num); PrintEven printEven = new PrintEven(num); Thread thread1 = new Thread(printOdd); Thread thread2 = new Thread(printEven); thread1.setName("奇数线程:"); thread2.setName("偶数线程:"); thread1.start(); thread2.start(); } }
用匿名内部类的方法,思路也是synchronized和wait和notify
package com.lcz.thread;import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;// 多线程:两个线程轮流打印1-100// 解题思路:synchronized以及wait和notifyclass MyThread{ int num = 1; // 方法 public void increase() { while(num<=100) { synchronized (this) { notify(); System.out.println(Thread.currentThread().getName()+" "+(num++)); try { wait(); }catch (InterruptedException e) { System.out.print(e.getMessage()); } } } }}public class Print_Odd_Even2 { public static void main(String[] args) { MyThread mythread = new MyThread(); new Thread(()-> { mythread.increase(); }).start(); new Thread(()-> { mythread.increase(); }).start(); } }
上面的锁的方式是隐式锁synchronized,这里我们用显式锁reentrantlock以及condition信号量
package com.lcz.thread;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;// 多线程:两个线程轮流打印1-100// 解题思路:synchronized以及wait和notifyclass MyThread{ int num = 1; ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); public void increase() { while(num <= 100) { try { lock.lock(); condition.signal(); System.out.println(Thread.currentThread().getName() + " " + num++); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } finally { lock.unlock(); } } }}public class Print_Odd_Even2 { public static void main(String[] args) { MyThread mythread = new MyThread(); new Thread(()-> { mythread.increase(); }).start(); new Thread(()-> { mythread.increase(); }).start(); } }
转载地址:http://ecwdf.baihongyu.com/