62,614
社区成员
发帖
与我相关
我的任务
分享
//====
//=========================== class ShareResource
//====
public class ShareResource
{
//------------------- main method
//----
public static void main(String[] args)
{
SumThread number1=new SumThread(1); //创建一个实现了Runnable接口的类的实例。
Thread thread1=new Thread(number1); //创建2个线程。
Thread thread2=new Thread(number1);
thread1.start(); //线程启动。
thread2.start();
}//end main
}
//=========================== end ShareResource
//
//====
//=========================== class SumThread
//====
class SumThread implements Runnable
{
int sum=0;
int num;
//------------------- constructor
//----
public SumThread(int num)
{
this.num=num;
}
//------------------- method run
//----
public void run()
{
for(int i=1;i<5;i++)
{
sum=sum+i;
System.out.println((new Thread(this)).currentThread().toString()+sum);
try
{
Thread.sleep((int)(Math.random()*50));
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}//end try catch
}//end for
System.out.println(sum);
}//end run
}
//=========================== end SumThread
写这个里面代码写在这里面就可以了