利用多线程编写程序:
员工张明有两个主管,主管A和主管B经常会根据张明的表现给他调工资,有可能增加或减少。试用两个线程来执行主管A和主管B给张明调工资的工作,请使用线程同步解决数据完整性问题。
分析:(1)编写雇员类:成员变量 员工编号,姓名,工资;
构造方法:创建员工对象
成员方法:读取员工工资getEmpSalary()、设置员工工资setEmpSalary(double salary)、showSalary()查看员工姓名和薪水的方法
(2)通过实现Runnable 接口来定义线程类,其中change()方法用来调整员工的工资。在run()方法中调用change(200)将员工的工资增加200元。
import java.util.Scanner;
public class gongzi {
public static void main(String[] args) {
TestSal c=new TestSal();
Thread yi=new Thread(c,"主管A");
Thread er=new Thread(c,"主管B");
yi.start();
try {
yi.join();
}
catch (InterruptedException e) {
}
er.start();
}
}
class yuangong{
private double bianhao,gongzi;
private String name;
public yuangong(double bianhao,double gongzi,String name ) {
this.bianhao=bianhao;
this.gongzi=gongzi;
this.name=name;
}
public double getEmpSalary() {
return gongzi;
}
public void setEmpsalary(double salary) {
this.gongzi=salary;
}
public void showSalary() {
System.out.println("姓名"+name+"薪水"+gongzi);
}
}
class TestSal implements Runnable{
yuangong a=new yuangong(10,300,"小李");
Scanner b=new Scanner(System.in);
double x=b.nextDouble();
public void run() {
change(x);
System.out.println(Thread.currentThread().getName());
a.showSalary();
}
private synchronized void change(double x2) {
double t= a.getEmpSalary();
a.setEmpsalary((t+x2));
}
}
假设某家银行可接受顾客的存款,每次进行一次存款,便可计算出存款的总额。现有两名顾客,每人分三次,每次存入100元。试编程来模拟顾客的存款操作。
public class cunkuan {
public static void main(String[] args) {
Customer c1 = new Customer();
Customer c2 = new Customer();
c1.start();
c2.start();
}
}
class Bank{
private static int balance = 0;
public synchronized static void take(int money) {
int temp = balance;
temp += money;
try {Thread.sleep((int)(1000*Math.random()));}
catch(InterruptedException e) {}
balance = temp;
System.out.println("银行总余额为:" + balance);
}
}
class Customer extends Thread{
public void run() {
for (int i = 0;i < 3;i++) {
Bank.take(100);
}
}
}