Threads and Anonymous Classes in JAVA
As we all know,a thread is a separate process on your computer.you can run multiple threads all at the same time.
multi-threaded code has the disadvantage of becoming quite complex very quickly,although java has some great classes for dealing
with multithreading and simplifying it.
Today we will just look at creating threads,along with using anonymous classes to simplify(or some would say,complexify)your code.
there are two methods to Creating Threads in Java
the first way is to extend the Thread class, override the run() method with the code you want to execute,
then create a new object from your class and call start().
the second method is to pass an implementation of the Runnable interface to the constructor of Thread,
then call start().
we will look at both of the method in turn.
1.Extending the Thread Class
the sample code ad bellow:
public class Worker extends Thread {
@Override
public void run() {
// Loop for ten iterations.
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
// Sleep for a while
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// Interrupted exception will occur if
// the Worker object's interrupt() method
// is called. interrupt() is inherited
// from the Thread class.
break;
}
}
}
}
As shown above, we have create a Worker class that extends Thread. And override the run() Method and put some code
in it. The code just loops repeatedly and outputs a method.
we've also used a static method of the thread class,sleep().
note:if you use sleep,you should have to catch InterruptedException.
In the code below,we create two worker class and call their inherited start() methods, both run at the same time,not one after the other
public class Application {
public static void main(String[] args) {
Worker worker1 = new Worker();
worker1.start();
Worker worker2 = new Worker();
worker2.start();
// You can call interrupt() if you want
// to interrupt a thread. The thread itself
// decides how to handle interrupts.
// worker1.interrupt();
}
}
screenshot as below:
0 looping ...
0 looping ...
1 looping ...
1 looping ...
2 looping ...
2 looping ...
3 looping ...
3 looping ...
4 looping ...
4 looping ...
5 looping ...
5 looping ...
6 looping ...
6 looping ...
7 looping ...
7 looping ...
8 looping ...
8 looping ...
9 looping ...
9 looping ...
the start() method, inherited from the parent Thread class, creates a new thread and runs whatever code is in run() in the new thread.
if not use the threads:
public class Application {
public static void main(String[] args) {
Worker worker1 = new Worker();
worker1.run();
Worker worker2 = new Worker();
worker2.run();
// You can call interrupt() if you want
// to interrupt a thread. The thread itself
// decides how to handle interrupts.
// worker1.interrupt();
}
}
result as below:
0 looping ...
1 looping ...
2 looping ...
3 looping ...
4 looping ...
5 looping ...
6 looping ...
7 looping ...
8 looping ...
9 looping ...
0 looping ...
1 looping ...
2 looping ...
3 looping ...
4 looping ...
5 looping ...
6 looping ...
7 looping ...
8 looping ...
9 looping ...
above code doesn't use multithreading, take twice as long to run.
2.passing code to Thread Directly
the second method of starting a thread is to put the code you want to run in the run method of a class that implements the Runnable interface, then pass it to
the constructor of a thread class
the code below does exactly that;we've put the code all in one file to make it easier to follow.
class CodeRunner implements Runnable {
@Override
public void run() {
// Loop for ten iterations.
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
// Sleep for a while
try {
Thread.sleep(200);
} catch (InterruptedException e) {
break;
}
}
}
}
public class Application {
public static void main(String[] args) {
CodeRunner runner = new CodeRunner();
Thread thread = new Thread(runner);
thread.start();
}
}
result:
0 looping ...
1 looping ...
2 looping ...
3 looping ...
4 looping ...
5 looping ...
6 looping ...
7 looping ...
8 looping ...
9 looping ...
we can simplify this code by calling new directly on our coderunner class,right where we create the thread.
Thread thread = new Thread(new CodeRunner());
thread.start();
3.Quick and Dirty Thread using Anonymous Class
in fact we can make this code even terser by creating a new intance of Runnable,sortof,directly in the Thread constructor.
Actually,we can't create a new intance of Runnable because it's an interface; so we can't do the follow:
// Won't work
Thread thread = new Thread(new Runnable());
thread.start();
but we can get this to work if we add in some curly brackets and implement the missing run() method in them.
// This works
Thread thread = new Thread(new Runnable() { @Override
public void run() { } }); thread.start();
of course, to get this code to do anything, we have to add some actual code to run.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
}
}
});
thread.start();
0 looping ...
1 looping ...
2 looping ...
3 looping ...
4 looping ...
5 looping ...
6 looping ...
7 looping ...
8 looping ...
9 looping ...
finally,we can make the code ecen more terse, if a little more cryptic,by not bothering to declare a variable to hold the thread class, and then
just calling the stat() method on it directly.
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
}
}
}).start();
here just to make the code a bit clearer.
if you are also interest in linux and android embed system,please connection with us in QQ group:139761394
Threads and Anonymous Classes in JAVA的更多相关文章
- java语言中的匿名类与lambda表达式介绍与总结 (Anonymous Classes and Lambda Expressions)
2017/6/30 转载写明出处:http://www.cnblogs.com/daren-lin/p/anonymous-classes-and-lambda-expressions-in-java ...
- JAVA匿名内部类(Anonymous Classes)
1.前言 匿名内部类在我们JAVA程序员的日常工作中经常要用到,但是很多时候也只是照本宣科地用,虽然也在用,但往往忽略了以下几点:为什么能这么用?匿名内部类的语法是怎样的?有哪些限制?因此,最近,我在 ...
- Unit Testing of Classes in Java
Every class can have a main method. That is a handy trick for unit testing of classes. For example, ...
- Replacing the deprecated Java JPEG classes for Java 7
[src: https://blog.idrsolutions.com/2012/05/replacing-the-deprecated-java-jpeg-classes-for-java-7/] ...
- Java基础之二十 并发
20.1 并发得多面性 并发编程令人困惑的一个主要原因:使用并发时需要解决的问题有多个,而实现并发的方法也有多种,并且在这两者之间没有明显的映射关系. 20.1.1 更快的执行 速度问题初听起来很简单 ...
- java--线程认识与实例记录 NO.1
下面的内容都是从java编程思想一书中摘取出来,我认为很有产考价值,并且便于后续使用. 主要内容是记录继承thread和实现runnable接口两种方式的代码用法,及内部类中启用线程的用法. 1.首先 ...
- 【Try Kotlin】Kotlin Koans 代码笔记
Kotlin Koans 心印 Introduction 1.Hello, world! Simple Functions Take a look at function syntax and mak ...
- Java8_02_lambda表达式
一.前言 这一节我们来了解下lambda表达式,主要关注以下几点: 行为参数化 匿名类 Lambda 表达式 方法 引用 二.行为参数化 1.概念 行为参数化(behavior parameteriz ...
- Java Inner Classes
When thinking about inner classes in java, the first thing that comes to my mind is that, WHY do we ...
随机推荐
- Hibernate学习之常用方法比较
一.save()和persist()方法 使用 save() 方法保存持久化对象时,该方法返回该持久化对象的标识属性值(即对应记录的主键值):但使用 persist() 方法来保存持久化对象时,该方法 ...
- 以Android环境为例的多线程学习笔记(二)-----------------锁和条件机制
现在的绝大多数应用程序都是多线程的程序,而当有两个或两个以上的线程需要对同一数据进行存取时,就会出现条件竞争,也即 是这几个线程中都会有一段修改该数据状态的代码.但是如果这些线程的运行顺序推行不当的话 ...
- python request模块学习
安装: pip install requests 使用: import requests HTTP请求:GET.POST.PUT.DELETE.HEAD.OPTIONS 1) get res = re ...
- Python的maketrans() 方法
描述 Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标. 注:两个字符 ...
- java使用验证码进行登录验证
随机生成4位验证码,将生成的4位数字字母数字放入session private static void outputVerifyCode(HttpServletRequest request, Htt ...
- Nuget升级问题
想在项目中通过“Add Library Package Reference”添加Moq,结果出现错误提示说Nuget版本太低. 要升级Nuget需要先卸载原来的Nuget. 1.在控制面板,卸载程序里 ...
- .net mvc笔记1_ The MVC Pattern
1.controller中的每一个public method被称为action method,意味着你可以从web上通过URL来调用它,以此来执行一个action. 2.当我们从action meth ...
- 把WinXP装进内存 性能飚升秒杀固态硬盘
现在用户新配置的电脑,内存很少有小于2GB的,配置4GB内存的朋友也有不少.容量如此大的内存,我们在使用电脑的日常操作中绝对用不完.而目前制约系统性能最大的瓶颈就是硬盘的传输速度,所以,这里教你怎么把 ...
- HDU 5059 Help him
题解:先判断第一个是否负号.如果是把第一个符号拿掉之后判断后面的长度是否<=12,并且是否数字,然后转化成数字看看是否在[a,b],注意-0这个数据. 如果不是判断长度是否<=12,并且是 ...
- 多名Uber司机被指刷单遭封号 一周薪水为0
昨天,一司机在Uber“司机之家”办公地墙上写了泄愤的话 摄/法制晚报记者 苏妮 司机展示的账单显示,上周的薪水几乎为零,上面用英文标注了“欺诈行为”的字样 摄/法制晚报记者 苏妮 法制晚报讯(记者 ...