网络编程技术次课多线程代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1)第一个程序:LeftAndRight.java
public class LeftAndRight {
public static void main(String args[]) {
Lefthand left;//声明线程类对象
Righthand right;
left = new Lefthand();// 新建线程。
right = new Righthand();
left.start(); // 线程开始运行后,Lefthand类中的run方法将被执行。
right.start();
for (int i = 0; i <= 6; i++) {
System.out.println("我是主线程");
}
}
}
class Lefthand extends Thread {
public void run() {
for (int i = 1; i <= 9; i++) {
System.out.println("我是左手线程");
try {//线程执行一次输出后,休眠500ms(毫秒),使自己放弃CPU资源,//500ms时间到后,重新排队等待CPU的调度
sleep(500);
} catch (InterruptedException e) {
//如果线程在休眠期被打断,将抛出InterruptedException,
//所以sleep方法需要在try……catch语句块中被调用
}
}
}
}
class Righthand extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("我是右手线程");
try {
sleep(300);
} catch (InterruptedException e) {
}
}
}
}
2)第二个程序:StudentAndTeacher.java
public class StudentAndTeacher {
/**
*两个线程共享一个对象ComputerSum sum,在运行的过程中修改这个对象的成员变量sum。
*为了使结果尽量不依赖于当前CPU资源的使用情况,应当让线程主动调用sleep方法,让出CPU的控制权进入中断状态
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ComputerSum sum = new ComputerSum();
People teacher = new People("教师", 100, sum);
People student = new People("学生", 100, sum);
teacher.start();
student.start();
}
}
class ComputerSum {
//线程共享的对象类ComputerSum,其中定义了一个数据成员sum
int sum=0;
public void setSum(int n) {
sum = n;
}
public int getSum() {
return sum;
}
}
class People extends Thread {
//类People是Thread的子类
ComputerSum computerSum;
int timeLength;
People(String s, int timeLength, ComputerSum sum) {//构造方法
setName(s);// 设置Thread的名称
this.timeLength = timeLength;//设置休眠时间
puterSum = sum;//设置ComputerSum类的对象sum }
public void run() {//重写Thread父类的run()方法
for (int i = 1; i <= 5; i++) {
int m = computerSum.getSum();//取出computerSum对象中的数据成员sum
computerSum.setSum(m+1);//将数据成员sum的值加1
System.out.println("我是" + getName() + ",现在的和是" + computerSum.getSum());
//输出当前处于运行中的线程的信息
try {
sleep(timeLength);//线程休眠timeLength毫秒
} catch (InterruptedException e) {
}
}
}
}
3)第三个程序:StudentAndTeacher1.java
public class StudentAndTeacher1 {
/**
*StudentAndTeacher1为StudentAndTeacher的改进版本
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ComputerSum sum = new ComputerSum();
People1 people = new People1(200, sum);
people.teacher.start();
people.student.start();
}
}
class ComputerSum1 {
// 线程共享的对象类ComputerSum,其中定义了一个数据成员sum
int sum = 0;
public void setSum(int n) {
sum = n;
}
public int getSum() {
return sum;
}
}
class People1 implements Runnable {
// 类People是Thread的子类
ComputerSum computerSum;
int timeLength;
Thread teacher, student;
People1(int timeLength, ComputerSum sum) {// 构造方法teacher = new Thread(this);//类People1实现了接口Runnable
teacher.setName("教师");
student = new Thread(this);
student.setName("学生");
this.timeLength = timeLength;// 设置休眠时间