多线程机制
多线程是指同时存在几个执行体,按照几条不同的执行线索共同工作的情况,使编程人员很方便的开发出具有多线程功能,能同时处理多个任务的功能强大的应用程序。
实现多线程的方式
一、继承Thread类
public class People extends Thread {
int timeLength;
Csum sum;
People(String s,int timeLength,Csum sum){
setName(s);
this.timeLength=timeLength;
this.sum=sum;
}
public void run(){
for (int i=1;i<=5;i++){
int m=sum.getSum();
sum.setSum(m+1);
System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
try {
sleep (timeLength);
}catch(InterruptedException e){}
}
}
}
int timeLength;
Csum sum;
People(String s,int timeLength,Csum sum){
setName(s);
this.timeLength=timeLength;
this.sum=sum;
}
public void run(){
for (int i=1;i<=5;i++){
int m=sum.getSum();
sum.setSum(m+1);
System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
try {
sleep (timeLength);
}catch(InterruptedException e){}
}
}
}
public class Csum {
int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Csum sum = new Csum();
People teacher = new People("老师",200,sum);
People student = new People("学生",200,sum);
teacher.start();
student.start();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Csum sum = new Csum();
People teacher = new People("老师",200,sum);
People student = new People("学生",200,sum);
teacher.start();
student.start();
}
}
二、实现Runnable接口
public class ThreadTest2 implements Runnable {
private int money = 0;
Thread account,casher;
ThreadTest2(){
account=new Thread(this);
account.setName("account");
casher=new Thread(this);
casher.setName("casher");
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true){
money =money-50;
if(Thread.currentThread()==account){
System.out.println("我是"+account.getName()+",现在有:"+money);
if(money<150){
System.out.println(account.getName()+"进入死亡状态");
return;
}
}
else if(Thread.currentThread()==casher){
System.out.println("我是"+casher.getName()+",现在有:"+money);
if(money<150){
System.out.println(casher.getName()+"进入死亡状态");
return;
}
}
try {
Thread.sleep (800);
}catch(InterruptedException e){}
}
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
public class Bank {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest2 test = new ThreadTest2();
test.setMoney(300);
test.account.start();
test.casher.start();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest2 test = new ThreadTest2();
test.setMoney(300);
test.account.start();
test.casher.start();
}
}