【线程三】【翻译】如何在Java中实现线程?

引言

在语言层面有两种方式。java.lang.Thread 类的实例就是一个线程但是它需要调用java.lang.Runnable接口来执行,由于线程类本身就是调用的Runnable接口所以你可以继承java.lang.Thread 类或者直接调用Runnable接口来重写run()方法实现线程。

In my opinion Thread is one of the most important feature of Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming class on India how important Thread was portrait(描绘) and how much emphasis(重要) given on clear understanding of multi-threading. Its still popular and one of most sought(seek,寻找,追求) after skill in Java programmer because writing concurrent(同时发生) and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. Main problem with using multiple threads and writing multi-threaded code is issues related to concurrency (并发,并行)

翻译:Java 线程很重要,编写并发执行的应用是一个挑战

e.g. deadlock, livelock, race conditions etc, It takes lot of effort to implement multi-threading correctly in Java application. In this core Java tutorial I will share my experience on different way of implementing Thread in Java;  By the way difference between Thread and Runnable in Java is also a very common core Javainterview question and asked mostly during junior level Java interview. After reading this tutorial, you will not only able to create and start thread but also able to answer what is difference in two ways of implementing thread in Java, by implementing Runnable interface or by extending Thread class.

例如 死锁,活锁,竞争条件等,它需要花很多精力去实现Java应用中的并行线程。

在java面试中,Runnable和Thread两种方式问的多,这篇方案不仅教你创建thread,也给你说明两者区别。

How to make Thread in Java

两种方式实现Java 线程

There are two ways of implementing threading in Java

1) By extending java.lang.Thread class, or
1)继承Thread类
2) By implementing java.lang.Runnable interface.
2)实现接口Runnable

Before we go into implementation details I just like to cover when we use Thread in Java?  So we use thread if we want some part of code is executed parallel (平行的)and we put that code inside run() method of either Thread class or Runnable interface.

在我们开始具体细节前,先说下什么时候我们用线程呢,就是当我们想让一些代码,同时运行的时候,我们就把这部分代码放在实现Java的那两种方式中的run()方法里面

Actually public void run() method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically. I remember by first Java multi threading example which was an animation program where multiple threads were used in Applet to create animation of words falling from top left, middle and top right of the page. That was pretty exciting at that time because till then I only know program which takes input from command prompt and print output on command prompt.

实际上,public void run() 方法是定义在Runnable接口和由于java.lang.Thread类实现Runnable接口,它也就获得了此方法。记得第一个Java多线程小程序,是一个卡通程序,用多线程创建了从左上角,页的中部和顶部右下降字的动画。这在当时是非常令人兴奋,因为那时我只知道程序需要在命令提示符中运行。

Java Thread Tutorial and Example

Java 线程教程+示例

第一步,先实现接口。

So now the interview question  which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

先讨论下,如果面试问,在Java中,继承Thread和实现Runnable哪种实现线程的方法好?如何回呢

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.

我觉得实现接口好,因为Java是单继承,多实现,所以如果继承了Thread,我们就不能再继承其它类,但是实现了一个接口,我们还可以实现其它接口,也可以继承其它一个类。

Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface. If you are still not convince on why implementing Runnable is better than extending Thread class for creating threads in Java, I think it’s time you should read this article.

还有,容易扩展。OO思想。

So first step is complete, you have implemented thread by now. Next step is to actually create object of thread class and start it. This is will create a separate path of execution parallel to main thread. Java thread is state based so it remains in predefined state at any given time and state transition occurs by calling different thread method. So, when you create object of your class which has implemented Runnable or extended Thread, you just create an object of Thread class, Thread will not start until you call the start() method of java.lang.Thread class. This is shown clearly in above thread state transition diagram in Java. It is now in NEW state, when we call start() method Java Virtual machine execute run() method of that Thread class it goes into RUNNBLE state. Now, it’s upto thread scheduler to assign CPU to this thread. From here on it can either complete its execution and go to TERMINATED state or can go into WAITING, TIMED WAITING and BLOCKED state. By the way if you notice, when we call start() method, it eventually calls run() method, can anybody guess what will happen if we call the run() method directly instead of calling start() method ?

第二步,如何起线程

先创建线程类,再起之。这个线程是个Main异步的,平行的。new一个实现了Runnable接口的类或者继承Thread的类,表明这个类是一个线程类,只有调用.start()方法后,这个线程才算可运行状态(RUNNBLE),至于啥时候跑,得看CPU啥时候调用调度器了(这个不可控,见什么是线程 第8点),然后接下来此线程可以完成,进行终止状态,或者等待,阻塞。

顺便说句,你稍微注意下,会知道当调用start的时候,其实最终到线程类中调用了run方法,知道怎么发生的吗?点击引言链接。

注:线程状态解释(Thread.State (Java Platform SE 7 )
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html)

That another popular multi-threading interview question and answer is simple there would be no Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start() method twice in same Thread object e.g.
另一个多线程面试题:你在一个类里面调用两次start方法,将会发生什么。

 

Bonus Tip 温馨提示

TIP1: Its not guaranteed that thread mythread will start before thread myrunnable it depends upon Thread scheduler.

 线程调度器不可控

TIP2: Thread will be said to go on dead state once execution of run() method finished and you can not start that thread again.

一旦线程执行完,就会死亡,你不能再把那个线程起来了

(Yol注:但是逻辑可以再起,那个线程不能起了。)

发表评论

电子邮件地址不会被公开。