首页 > 代码库 > 线程组、等待唤醒机制代码优化
线程组、等待唤醒机制代码优化
线程组: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(); } }
线程组、等待唤醒机制代码优化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。