JAVA中线程怎么使用啊

来源:百度知道 编辑:UC知道 时间:2024/05/28 17:50:12
不会用 比如用它做个ATM取款机什么的例子给看下

class test {
private static int s = 2000;
public synchronized static void sub(int m){//自定义方法,可以类比于自定义异常
int temp = s;
temp = temp - m;
try {
Thread.sleep((int)(Math.random() * 1000));
}catch (Exception e){
System.out.println(e.getMessage());
}
s = temp;
System.out.println("s = " + s);
}
}

class Customer extends Thread{
public void run(){//调用run()方法,运行run()方法中的程序片
for(int i = 1;i <= 4;i++){
test.sub(100);
//当线程cus1没有结束对sub方法的使用之前,cus2无法进入并运行此方法
//synchronized的作用就在于此
}
}
}

public class Synchronizedtest{
public static void main(String[] args){
Customer cus1 = new Customer();
Customer cus2 = new Customer();
cus1.start();
cus2.start();
}
}

自己研究下吧

线程据我所知在开发大型项目的时候才会用到