学习笔记(二)多线程

本文探讨了多线程的原理,详细解析了实现多线程的多种方法,帮助读者掌握并发编程的核心知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多线程机制

多线程是指同时存在几个执行体,按照几条不同的执行线索共同工作的情况,使编程人员很方便的开发出具有多线程功能,能同时处理多个任务的功能强大的应用程序。

实现多线程的方式

一、继承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){}
}
}
}

public class Csum {
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();

}
}

二、实现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();
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值