线程组等待唤醒机制代码优化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程组等待唤醒机制代码优化相关的知识,希望对你有一定的参考价值。
线程组:ThreadGroup
把多个线程组合到一起,可以对一批线程进行分类处理,JAVA允许程序直接对线程进行控制
获取线程组:public final ThreadGroup getThreadGroup()
获取线程组的名称:public final String getName()
设置新的线程组:ThreadGroup(String name)
把线程弄到新线程组里:Thread(ThreadGroup group,Runnable target,String name)
等待唤醒机制代码优化
package cn.idcast6; public class Student { private String name; private int age; private boolean flag; public synchronized void set(String name, int age) { if (this.flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.name = name; this.age = age; this.flag = true; this.notify(); } public synchronized void get() { if (!this.flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(this.name+"----"+this.age); } this.flag = false; this.notify(); } }
package cn.idcast6; public class SetStudent implements Runnable { private Student s; public SetStudent(Student s) { this.s = s; } private int x = 0; @Override public void run() { // TODO Auto-generated method stub while (true) { if (x % 2 == 0) { s.set("林青霞", 19); } else { s.set("留意", 1); } x++; } } }
package cn.idcast6; public class GetStudent implements Runnable { private Student s; public GetStudent(Student s) { this.s=s; } @Override public void run() { // TODO Auto-generated method stub while(true) { s.get(); } } }
package cn.idcast6; public class StudentDemo { public static void main(String[] args) { Student s = new Student(); SetStudent ss = new SetStudent(s); GetStudent gs = new GetStudent(s); Thread t1 = new Thread(gs); Thread t2 = new Thread(ss); t1.start(); t2.start(); } }
以上是关于线程组等待唤醒机制代码优化的主要内容,如果未能解决你的问题,请参考以下文章
JAVA-初步认识-第十四章-线程间通信-等待唤醒机制-代码优化
死锁Lock锁等待唤醒机制线程组线程池定时器单例设计模式_DAY24
阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第4节 等待唤醒机制_8_等待唤醒机制代码实现_包子类&包子铺类