黑马程序员技术交流社区
标题:
【记录】代码练习-线程间通信
[打印本页]
作者:
Kevin.Kang
时间:
2015-8-5 14:44
标题:
【记录】代码练习-线程间通信
本帖最后由 Kevin.Kang 于 2015-8-5 15:03 编辑
针对同一资源有不同的线程进行操作
例如:卖票,需要有卖票的进程,还需要有生产票的进程
通过对学生信息的设置和获取,写一个简单的线程间通信案例
测试类:StudentDemo
package com.kxg_13;
/*
* 资源类:Student
* 设置学生信息:SetThread
* 获取学生信息:GetThread
* 测试类:StudentDemo
*
* 注意:
* 设置和获取线程使用的资源应该是同一个,所以把这个资源在外界创建出来,通过构造方法传递给其他类。
*
*/
public class StudentDemo {
public static void main(String[] args) {
// 创建资源
Student s = new Student();
// 创建Set和Get对象
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
// 创建线程
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
// 开启线程
t1.start();
t2.start();
}
}
复制代码
资源类:Student
package com.kxg_13;
/*
* 定义学生类
*/
public class Student {
String name;
int age;
}
复制代码
设置学生信息:SetThread
package com.kxg_13;
/*
* 设置学生信息的线程
*/
public class SetThread implements Runnable {
private Student s;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
s.name = "小明";
s.age = 5;
}
}
复制代码
获取学生信息:GetThread
package com.kxg_13;
/*
* 设置获取学生信息的线程
*/
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
System.out.println(s.name + ":" + s.age);
}
}
复制代码
作者:
Kevin.Kang
时间:
2015-8-5 18:13
最终版:
测试类:
package com.kxg_03;
public class StudentDemo {
public static void main(String[] args) {
// 创建资源
Student s = new Student();
// 创建SetThread和GetThread对象
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
// 创建线程
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
// 开启线程
t1.start();
t2.start();
}
}
复制代码
资源类:
package com.kxg_03;
/*
* 定义学生类
*/
public class Student {
String name;
int age;
boolean flag;// 用来判断是否存在资源,默认是flash,没有资源
public synchronized void set(String name, int age) {
// 生产者,如果有数据就等待
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 设置数据
this.name = name;
this.age = age;
// 修改标记
this.flag = false;
// 唤醒线程
this.notify();
}
public synchronized void get() {
if (this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name + ":" + this.age);
// 修改标记
this.flag = true;
// 唤醒线程
this.notify();
}
}
复制代码
设置类:
package com.kxg_03;
/*
* 设置学生信息的线程
*/
public class SetThread implements Runnable {
private Student s;
private int i;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
if (i % 2 == 0) {
s.set("小明", 5);
} else {
s.set("汪汪", 2);
}
i++;
}
}
}
复制代码
获取类:
package com.kxg_03;
/*
* 设置获取学生信息的线程
*/
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2