求教下大家,是不是一个类只能创建一个main线程和一个run为入口的线程?如果我要为其他代码创建一个线程,就必须新建一个类然后再附带一个run方法?最后在main中创建不同类的实例去创建不同代码的线程?
如果要在一个类里创建若干个不同代码的线程要如何做?感觉start()的入口只有一个,run()...

解决方案 »

  1.   

    不行吧  一个类里只能有一个run方法 应该一个类只能是一个线程
      

  2.   

    谢谢ls的,请看以下代码:public class threadExam{
     static int x=0;
     
      public static class mythread1 implements Runnable{
      threadExam commonObj;
    public mythread1(threadExam obj){
    commonObj=obj;
    }
     public void run(){

    while(x<10){
    System.out.println(Thread.currentThread().getName()+",value of x is:"+commonObj.x);
    x++;

    } }
     }
      public static class mythread2 implements Runnable{
      threadExam commonObj;
    public mythread2(threadExam obj){
    commonObj=obj;
    }
     public void run(){
     x=x-1;
     System.out.println(Thread.currentThread().getName()+",x="+commonObj.x);
    }
    public static void main(String []args){
    threadExam d=new threadExam();
    mythread1 r1=new mythread1(d);
    Thread t1=new Thread(r1,"Pig");
    mythread2 r2=new mythread2(d);
    Thread t2=new Thread(r2);
    t2.setName("Rabbit");
    t1.start();
    t2.start();

    }
    }
    }被抛出:
    java.lang.NoSuchMethodError: main
    Exception in thread "main" 
    的异常,能帮看下错在哪么?
      

  3.   

    public class threadExam{
     static int x=0;
     
      public static class mythread1 implements Runnable{
      threadExam commonObj;
    public mythread1(threadExam obj){
    commonObj=obj;
    }
     public void run(){
    while(x<10){
    System.out.println(Thread.currentThread().getName()+",value of x is:"+commonObj.x);
    x++;
    }
        }
     }
      public static class mythread2 implements Runnable{
        threadExam commonObj;
    public mythread2(threadExam obj){
    commonObj=obj;
    }
    public void run(){
     x=x-1;
     System.out.println(Thread.currentThread().getName()+",x="+commonObj.x);
    }
      }
    public static void main(String []args){
    threadExam d=new threadExam();
    mythread1 r1=new mythread1(d);
    Thread t1=new Thread(r1,"Pig");
    mythread2 r2=new mythread2(d);
    Thread t2=new Thread(r2);
    t2.setName("Rabbit");
    t1.start();
    t2.start();

    }}
    可以了,原因是大括号不匹配...哎,习惯不好啊~