One: Inheriting the thread class creating a threading Class
Class Primethread extends Thread {
long minprime;
Primethread (Long minprime) {
this.minprime = minprime;
}
public void Run () {
//compute primes larger than minprime ...
}
}
The following code would then create a thread and start it running:
primethread p = new Primethread (143);
P.start ();
Two: Implement Runnable interface Create thread class (introduction in JAVA API)
Class Primerun implements Runnable {
long minprime;
Primerun (Long minprime) {
this.minprime = minprime;
}
public void Run () {
//compute primes larger than minprime ...
}
}
The following code would then create a thread and start it running:
primerun p = new Primerun (143);
New Thread (P). Start ();
Three: Creating threads using callable and Futuretask
The callable object is created using a lambda expression and then wrapped using Futuretask
Futuretask task = new Futuretask (callable) ()-> {
int i = 0;
for (; i < i++) {System.out.println (
thread.currentthread (). GetName () + The value of the loop variable I: +i);
return i;
});
Creating Threads
New Thread (Task, "Thread with return value"). Start ();
Four: Three ways to create a thread comparison
The way to implement the Runnable interface and the Calable interface is basically the same, the Knowledge Calable interface defines a method that has a return value and can declare an exception to be thrown. So they are grouped into one category. The difference between this approach and the inheritance thread approach is as follows:
@ Create the pros and cons of multithreading in the way that implements the interface:
1 The thread class knowledge implements the Runnable interface or the Calable interface, and can also inherit other classes.
2 in this way, multiple threads can share a target object, ideally suited for multiple identical threads to handle the same resource.
3 Disadvantage is: Programming comparison of the trouble, if you need to access the current thread, you need to call the CurrentThread () method.
@ Use the inheritance thread class to create the advantages and disadvantages of multithreading:
1 The disadvantage is that the thread class has been inherited, so you cannot inherit other parent classes.
2 Advantage is: The code is simple, you can access the current thread directly through this.
Through analysis, it is generally recommended to implement the interface to create multithreading.
Article source http://blog.sina.com.cn/s/blog_e3734cfe0102xsoo.html