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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微个日光日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值