2011-03-22 71 views
0

我是Java的新手,想知道我是否可以按照以下方式创建线程。在Java中创建线程

需要的Java代码:

Class MyClass { 

    Myclass(){ 
     Statement1;//Create a thread1 to call a function 
     Statement2;//Create a thread2 to call a function 
     Statement3;//Create a thread3 to call a function 
    } 
} 

是否有可能创建一个类似上面的代码线程?

回答

1

呼应GregInYEG,你应该检查出的教程,但是可以简单的解释如下:

您需要创建或者继承Thread或实现Runnable对象类。在这个类中,创建(实际上是重载)一个名为“run”的无效方法。在这个方法里面,你放置了代码,你希望这个线程在分叉之后执行。如果你愿意,它可以简单地调用另一个函数。然后,当你想产生一个这种类型的线程时,创建这些对象中的一个,并调用这个对象的“start”(不是run!)方法。例如newThread.start();

调用“开始”而不是“运行”是很重要的,因为运行调用将像调用其他任何方法一样简单地调用方法,而不会分叉新线程。

尽管如此,请务必详细阅读并且还有许多重要的并发性方面,尤其是锁定共享资源的方面。

3

Java Concurrency tutorialdefining and starting threads上包含一页。您可能需要在并发教程中与其他页面一起阅读它。

+0

尤其是部分“高级别的并发对象使用这两种方法“可能是有价值的。通常较高级别的对象更易于使用。 – 2011-03-22 21:30:35

+0

不能完全理解他们中的任何一个。创建一个空的runnable类并尝试从不同的类调用2个不同的函数。 Eclipse甚至不允许我写这个类 – 2011-03-22 21:45:33

0

是的,这是可能的。您希望将您的逻辑用于Runnable实施中的每个语句,然后将每个构建的Runnable传递给Thread的新实例。看看这两个类,它应该变得相当明显,你需要做什么。

0

我同意所有写在这里。该线程可以通过两种方式创建。

  1. 扩展线程类。 YouTube Tutorial
  2. 为了实现Runnable接口YouTube Tutorial

实施例为第一方法

public class MyThread extends Thread { 


public void run() 
{ 
    int iterations = 4; 


     for(int i=0;i<iterations;i++) 
     { 

      System.out.println("Created Thread is running " + Thread.currentThread().getId() + " Printing " + i) ; 
      try { 
       sleep(3000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       System.err.println(e); 
      } 
     } 


    System.out.println("End of program"); 
} 

}

要创建一个线程

MyThread myThread = new MyThread(); 

myThread.start(); 

第二方法来实现可运行接口

public class RunnableThread implements Runnable { 

@Override 
public void run() { 

    int iterations = 4; 


    for(int i=0;i<iterations;i++) 
    { 

     System.out.println("Runnable Thread is running " + Thread.currentThread().getId() + " Printing " + i) ; 
     try { 
      Thread.sleep(3000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.err.println(e); 
     } 
    } 


System.out.println("End of program"); 
} 

}

要创建一个线程

new Thread(new RunnableThread()).start(); 

所以我认为你可以在你的case语句