用Java创建线程

时间:2011-03-22 21:21:55

标签: java multithreading

我是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
    }
}

是否可以像上面的代码一样创建线程?

4 个答案:

答案 0 :(得分:3)

Java Concurrency tutorial包含defining and starting threads上的页面。您可能希望将其与并发教程中的其他页面一起阅读。

答案 1 :(得分:1)

回应GregInYEG,你应该查看教程,但简单的解释如下:

您需要创建一个扩展Thread或实现Runnable的对象类。在这个类中,创建(实际上,重载)一个名为“run”的void方法。在此方法中,您可以放置​​您希望此线程在分叉后执行的代码。如果你愿意的话,它可以简单地调用另一个函数。然后,当您想要生成此类型的线程时,创建其中一个对象并调用此对象的“start”(不运行!)方法。例如newThread.start();

调用“start”而不是“run”是很重要的,因为运行调用只会调用方法,而不需要新的线程。

但是,请务必进一步详细阅读,并发更多重要的并发方面,特别是锁定共享资源的方面。

答案 2 :(得分:0)

是的,有可能。您希望将每个语句的逻辑放在Runnable实现中,然后将每个构造的Runnable传递给Thread的新实例。查看这两个类,你应该做的很明显。

答案 3 :(得分:0)

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

  1. 扩展线程类。 YouTube Tutorial
  2. 实施Runnable Interface YouTube Tutorial
  3. 第一种方法的例子

    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();
    

    实现runnable接口的第二种方法

    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();
    

    所以我认为你可以在案例陈述中使用这两种方法