A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 丁一 中级黑马   /  2013-3-22 09:45  /  1967 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 丁一 于 2013-3-22 10:59 编辑

代码贴不全,就不用代码形式了,大神们将就看吧

class TestThread implements Runnable   
{
        public void run()  //
        {
                for(int j=0;j<50;j++)
                {
                        System.out.println("runing"+j);
                }
        }  //接口方式也必须有run()方法,调用时同样适用start()
}

public class Cs {
        public static void main(String [] args)
        {               
                        TestThread t =new TestThread();
                       
                        Thread tt = new Thread(t);// 用这个就出现错误
                        tt.start();
                        tt.start();

                        
                        /*new Thread(t).start();// 用这个就正常,
                        new Thread(t).start();*/
                       new Thread(t).start();*/


                        for (int i=0;i<50;i++)
                        {
                                System.out.println("main running"+i);
                        }
               
        }

}

评分

参与人数 1技术分 +1 收起 理由
洪建超 + 1

查看全部评分

7 个回复

倒序浏览
先把Cs类前面加上public,就可以运行了
  1. public class Cs {
  2.         public static void main(String [] args)
  3.         {               
  4.                         TestThread t =new TestThread();

  5. //创建多线程是不是只能用 new Thread(t).start(); 这个方式
  6. new Thread(t).start();
  7. new Thread(t).start();
  8.         }
  9. }
复制代码
回复 使用道具 举报
对了,实现Runnable接口也可以实现线程
  1. public class RunnableTest
  2. {
  3.   public static void main(String[] args){
  4.     PrintA pa = new PrintA();
  5.     //利用Thread(Runnable)的创建函数实现线程
  6.     Thread tr = new Thread(pa);
  7.     tr.start();
  8.     for(int i =0;i<10;i++){
  9.      System.out.println("b");
  10.     }
  11.   }
  12. }

  13. //继承Runnable接口
  14. class PrintA implements Runnable
  15. {
  16.     public void run(){
  17.      for(int i=0;i<10;i++){
  18.        System.out.println("a");
  19.      }
  20.     }
  21. }
复制代码
回复 使用道具 举报
TestThread这个类不是线程类,只是实现了Runnable接口,有自己的run方法
只有Thread及其子类才有start方法,star方法的作用是调用自己的run方法,并开启线程
建议LZ再看视频弄清楚线程创建的两种方式
回复 使用道具 举报
Thread tt = new Thread(t);// 用这个就出现错误
                        tt.start();
                        tt.start();

上面的出现错误,是因为, 同一个线程对象,调用了两次start 方法,一个线程已经启动,你还调用start 方法 肯定报错啊

/*new Thread(t).start();// 用这个就正常,
                        new Thread(t).start();*/
                       new Thread(t).start();*/

这个正常,是因为你 new 了 两次啊  两个不   同的对象 调用了两次start 方法 等于 又启动了 两个 线程 所以不报错

回复 使用道具 举报
蔡志刚 发表于 2013-3-22 10:52
Thread tt = new Thread(t);// 用这个就出现错误
                        tt.start();
                   ...

这样啊,我说的呢,3Q
回复 使用道具 举报
丁一 发表于 2013-3-22 10:58
这样啊,我说的呢,3Q

客气了 相互 帮助吧
回复 使用道具 举报
以前看视频太马虎了,视频中果然讲这个问题了 java 基础11天08
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马