Starting Threads and Using Anonymous Classes

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 also interest in linux and android embed system,please connection with us in QQ grounp:139761394

Starting Threads and Using Anonymous Classes,布布扣,bubuko.com

时间: 2024-08-10 02:09:47

Starting Threads and Using Anonymous Classes的相关文章

When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions

As mentioned in the section  Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code. Local classes, anonymous classes, an

JAVA匿名内部类(Anonymous Classes)

匿名内部类在我们JAVA程序员的日常工作中经常要用到,但是很多时候也只是照本宣科地用,虽然也在用,但往往忽略了以下几点:为什么能这么用?匿名内部类的语法是怎样的?有哪些限制?因此,最近,我在完成了手头的开发任务后,查阅了一下JAVA官方文档,将匿名内部类的使用进行了一下总结,案例也摘自官方文档.感兴趣的可以查阅官方文档(https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html). 2.匿名内部类 匿名内部类

[转]Activitys, Threads, &amp; Memory Leaks

转自:http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html http://www.cnblogs.com/kissazi2/p/4125356.html A common difficulty in Android programming is coordinating long-running tasks over the Activity lifecycle and avoiding

How to Leak a Context: Handlers & Inner Classes

Consider the following code: public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Handler() { @Override public void handleMessage(Message msg) { // ... } } } While not readily obvious, this code can cause cause a m

[转]How to Leak a Context: Handlers &amp; Inner Classes

Consider the following code: public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Handler() { @Override public void handleMessage(Message msg) { // ... } } } While not readily obvious, this code can cause cause a m

How to Write Doc Comments for the Javadoc Tool

http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describes the style guide, tag and image conventions we use in documentation comments for Java programs written at Java Software, Oracle. It does not rehash r

java的GC与内存泄漏

从诞生至今,20多年过去,Java至今仍是使用最为广泛的语言.这仰赖于Java提供的各种技术和特性,让开发人员能优雅的编写高效的程序.今天我们就来说说Java的一项基本但非常重要的技术内存管理 了解C语言的同学都知道,在C语言中内存的开辟和释放都是由我们自己来管理的,每一个new操作都要对于一个delete操作,否则就会参数内存泄漏和溢出的问题,导致非常槽糕的后果.但在Java开发过程中,则完全不需要担心这个问题.因为jvm提供了自动内存管理的机制.内存管理的工作由jvm帮我们完成.这样我们就不

Java 内存泄漏--全解析和处理办法 [ 转载 ]

Java内存泄露——全解析和处理办法 [转载] @author 小筐子 @address http://www.jianshu.com/p/bf159a9c391a 本文章会一步一步的探讨内存泄露的问题.博主第一次书写长篇技术贴,如有错误或不周到的地方请多指教. JAVA是垃圾回收语言的一种,开发者无需特意管理内存分配.但是JAVA中还是存在着许多内存泄露的可能性,如果不好好处理内存泄露,会导致APP内存单元无法释放被浪费掉,最终导致内存全部占据堆栈(heap)挤爆进而程序崩溃. 内存泄露 说到

类加载器泄露学习(三)杀死线程—— Classloader leaks III – “Die Thread, die!”

In my previous post we looked at different categories of ClassLoader leaks, and looked at a particular example of a reference from outside the web application ClassLoader (a JVM shutdown hook pointing to a JAI class). In this post we will look at ano