日期:2014-05-20  浏览次数:20775 次

多线程的问题
第一个是总是出现要输入参数,但那时程序已经结束了
第二个是不像预先想像的那样,两个线程同时的进行,来显示在文本框中

第一个程序
import   java.io.*;

public   class   TestThread  
{
public   static   void   main(String   args[])
{
if(args.length   <   1)
{
System.out.println( "please   enter   a   cmd   parameter   : ");
System.exit(0);
}

MyThread   myThread   =   new   MyThread(Integer.parseInt(args[0]));
myThread.start();
while(myThread.isAlive()   &&   myThread.readyToGoOn())
{
System.out.println( "Counting   the   number.... ");//so   the   main   thread   is   running
try
{
Thread.sleep(500);
}
catch(InterruptedException   e)
{
return;
}//End   of   catch
}//End   of   while
System.out.println( "按任意键继续.... ");
try
{
System.in.read();
}
catch(IOException   e){}
}
}
//create   the   user 's   thread   class
class   MyThread   extends   Thread
{
boolean   m_bContinue   =   true;//mark   the   end   of   the   thread
int   m_nCircleNum;//the   upmost   of   circle

MyThread   (int   Num)//construction   function
{
this.m_nCircleNum   =   Num;
}
boolean   readyToGoOn()//check   the   thread   is   to   run
{
return   m_bContinue;
}
public   void   run()//override   the   run   function   of   the   baseclass
{
int   number   =   3;
boolean   flag   =   true;

while(true)
{
int   i;
for(i   =   2;i   <   number;i++)
if(number   %   i   ==   0)
flag   =   false;
if(flag)
System.out.println(number   +   "是素数 ");
else
System.out.println(number   +   "不是素数 ");
number   ++;
if(number   >   m_nCircleNum)
{
m_bContinue   =   false;  
}
flag   =   true;
try
{
Thread.sleep(500);
}
catch(InterruptedException   e)
{
return;
}//End   of   catch
}//End   of   while
}//End   of   run
}//End   of   class
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
第二个程序
import   java.applet.Applet;
import   java.awt.*;

public   class   TestRunnable   extends   Applet   implements   Runnable
{
Label   prompt1   =   new   Label( "第一个子线程 ");
Label   prompt2   =   new   Label( "第二个子线程 ");
TextField   threadFirst   =   new   TextField(20);
TextField   threadSecond   =   new   TextField(20);
Thread   thread1,thread2;
int   count1   =   0,count2   =   0;
public   void   init()
{
add(prompt1);
add(threadFirst);
add(prompt2);
add(threadSecond);
}
public   void   start()
{
thread1   =   new   Thread(this, "First   Thread ");
thread2   =   new   Thread(this, "Second   Thread ");