码迷,mamicode.com
首页 > 编程语言 > 详细

线程组、等待唤醒机制代码优化

时间:2017-03-04 15:31:06      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:notify   rup   target   eth   获取   start   method   art   设置   

线程组: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();
	}

}

  

线程组、等待唤醒机制代码优化

标签:notify   rup   target   eth   获取   start   method   art   设置   

原文地址:http://www.cnblogs.com/zengjiao/p/6501420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!