Achieve Runable Interface

step

Runable define a class that implements the interface, implement run () method (method thread execution event) in the class.
Creating a class of objects above: Thread t = new Thread (new MyThreadt.start ());
call start method: t.start ();
Example:

public class Main2 implements Runnable {
int a;
Main2(int a) {
this.a = a;
}
@Override
public void run() {
while (true) System.out.println(a);
}
public static void main(String[] args) {
Thread t = new Thread(new Main2(1));
t.start();
Thread t2 = new Thread(new Main2(2));
t2.start();
}

}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
16
. 17
implement Runnable Thread class inheritance than the advantages:
for the same plurality of threads to process the same program code resource

Restrictions to avoid single inheritance in java

Increasing process robustness, code can be shared by multiple threads, separate code and data

Thread pool can only achieve Runable into thread or callable class, not directly into the inheritance Thread class
---------------------

Guess you like

Origin www.cnblogs.com/liyanyan665/p/11359757.html