Java线程基础知识 [英] Java Threading Basics

查看:105
本文介绍了Java线程基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面两个线程调用有什么区别?
这两个电话会同样行事吗?

What is the difference between the two thread calls below? Will the two calls act similarly?

注意:我没有使用#1& #2同时,这是最好的选择。

NOTE: I am not using #1 & #2 at the same time, which is the best option.

private void startConnections(){
    ServerThread server = new ServerThread();
    server.start(); // #1
    Thread serverThread = new Thread(server);
    serverThread.start(); //#2
}

class ServerThread extends Thread{
    public void run(){}
}


推荐答案

第一种方法是可以接受的,但不鼓励。第二个有效,但很难理解。考虑第三个:

The first approach is acceptable, but discouraged. The second one works, but is broken/hard to understand. Consider the third one:

class ServerRunnable implements Runnable {
  public void run(){}
}

Runnable run = new ServerRunnable();
Thread serverThread = new Thread(run);
serverThread.start();  //#3



#1



这是非常常见的方法 - 为了创建一个新线程,您只需将其子类化并调用 start()方法。许多人,包括我自己,都觉得这个习惯用法很糟糕 - 它不必要地将任务( run()方法的内容)与线程相结合( Thread class)。

#1

This is pretty common approach - in order to create a new thread you are simply subclassing it and calling start() method. Many people, including myself, find this idiom being a poor practice - it unnecessarily couples task (contents of run() method) with threading (Thread class).

我从未见过这样的代码,虽然技术上有效,我会立即纠正。即使您正在创建线程实例,您也会将其传递给另一个线程并启动后者。那么为什么要在第一个位置创建第一个线程呢?请注意, Thread 也实现了 Runnable ,所以它在技术上有效,但实在很尴尬。

I have never seen code like this and although technically working, I would correct it immediately. Even though you are creating a thread instance, you are passing it to another thread and starting the latter. So why creating the first thread on the first place? Note that Thread also implements Runnable, so it technically works, but is really awkward.

那么我推荐什么?实现 Runnable 未与线程耦合的接口。您不能单独在一个单独的线程中运行 Runnable ,您必须显式创建该线程。但是使用原始 Runnable 还可以让您轻松地从本机线程切换到例如线程池。

So what do I recommend? Implement Runnable interface that is not coupled to threading. You cannot run Runnable in a separate thread alone, you have to explicitly create that thread. But having raw Runnable also allows you to easily switch from native thread to for instance thread-pool.

从技术上讲,你可以扩展 Thread 并将这样的runnable放在一个线程池中,但是这很难理解,你也不必携带 Thread 行李(这是一个很大的课程)。

Technically you can extend Thread and put such a "runnable" in a thread pool, but this is really hard to understand and you are also unnecessarily carrying Thread baggage (it is quite a big class).

这篇关于Java线程基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆