在 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
}
}
是否可以像上面的代码一样创建线程?
I am a newbie to Java and wondering whether I can create threads in following way.
Desired Java Code :
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
}
}
Is it possible to create threads like the above code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 并发教程 包含关于 定义和启动线程。您可能需要将其与并发教程中的其他页面一起阅读。
The Java Concurrency tutorial includes a page on defining and starting threads. You might want to read through it along with the other pages in the concurrency tutorial.
与 GregInYEG 相呼应,您应该查看教程,但简单的解释如下:
您需要创建一个扩展 Thread 或实现 Runnable 的对象类。在此类中,创建(实际上是重载)一个名为“run”的 void 方法。在这个方法中,您可以放置希望该线程在分叉后执行的代码。如果您愿意,它可以只是对另一个函数的调用。然后,当您想要生成这种类型的线程时,创建这些对象之一并调用该对象的“start”(而不是运行!)方法。例如 newThread.start();
调用“start”而不是“run”很重要,因为 run 调用只会像其他方法一样调用该方法,而不会分叉新线程。
不过,请务必进一步详细阅读,并发性还有许多更重要的方面,尤其是锁定共享资源。
Echoing GregInYEG, you should check out the tutorial, but the simple explanation is as follows:
You need to create an object class which either extends Thread or implements Runnable. In this class, create (actually, overload) a void method called "run." Inside this method is where you put the code that you would like this thread to execute once it is forked. It could simply be a call to another function if you wish. Then, when you would like to spawn a thread of this type, create one of these objects and call the "start" (not run!) method of this object. eg newThread.start();
It's important to call "start" and not "run" because a run call will simply call the method just like any other, without forking a new thread.
Still, be sure to read up in further detail and there are many more important aspects of concurrency, especially that of locking shared resources.
是的,这是可能的。您希望将每个语句的逻辑放入
Runnable
实现,然后将每个构建的Runnable
传递给线程
。查看这两个类,您需要做什么应该变得相当明显。Yes, it is possible. You want to put your logic for each statement inside a
Runnable
implementation, and then pass each constructedRunnable
to a new instance ofThread
. Check out those 2 classes and it should become fairly obvious what you need to do.我同意这里写的所有内容。可以通过两种方式创建线程。
第一种方法的示例
}
创建线程
实现可运行接口的第二种方法
}
创建线程
所以我认为您可以在 case 语句中使用这两种方法
I agree with all written here. The thread can be created in a two ways.
Example for the first method
}
To create a thread
Second method to implement runnable interface
}
To create a thread
So I think you can use both of these methods in you case statements