关于线程的小问题.路过的大侠帮我看下

gnodw 2004-05-11 05:37:11
import java.io.*;

public class ATM{
public static void main(String args[]){
ThreadA thread1=new ThreadA();
Thread thread2=new Thread(new ThreadB(),"SecondThread");
thread1.start();

try{
Thread.sleep(5000);
}
catch (InterruptedException e){
return;
}
if(thread1.isAlive())
{
thread1.stop();

thread2.start();
try{
Thread.sleep(5000);
}catch (InterruptedException e){
return;
}

if(thread2.isAlive())
thread2.stop();
else
System.out.println("程序结束按任意键继续!");
try{
System.in.read();
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}




class ThreadA extends Thread

{
int M=200;
ThreadA(){}
public void run()
{
System.out.println("您的帐户余额为:"+M);
try{
sleep(2000);
}catch (InterruptedException e)
{M=M+100;
return;
}
try{
sleep(2000);
}catch (InterruptedException e)
{
return;
}
System.out.println("您的帐户余额为:"+M);
}
}


class ThreadB implements Runnable{
int M;
ThreadB(){}
public void run(){
System.out.println("您的余额为"+M);
try {
Thread.sleep(2000);
}catch (InterruptedException e)
{M=M-50;
return;
}
System.out.println("您的帐户余额为:"+M);
}
}
}
...全文
58 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
江南愚子 2004-05-11
  • 打赏
  • 举报
回复
你的类ThreadA和ThreadB放在类ATM中定义的话,就不能在静态(static)方法中创建它们的对象,如果一定要这么做,只能将类ThreadA和ThreadB放到类ATM外面去
gnodw 2004-05-11
  • 打赏
  • 举报
回复
................
gnodw 2004-05-11
  • 打赏
  • 举报
回复
ThreadA thread1=new ThreadA();
Thread thread2=new Thread(new ThreadB(),"SecondThread");
这2句出错C:\Program Files\Xinox Software\JCreator Pro\MyProjects\ATM.java:6: non-static variable this cannot be referenced from a static context ThreadA thread1=new ThreadA();
gnodw 2004-05-11
  • 打赏
  • 举报
回复
ps:变量M的范围我也搞不懂.能不能只定义一次

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧