Java as much as two-thread (implement Runnable)



/ **
* Create multi-threaded way: implement Runnable
* 1. Create a class that implements the Runnable interface
* 2. Implement Runnable class to implement abstract methods in: RUN ()
* 3. create an object implementation class
* 4. this object is passed as an argument to the constructor of the thread class, create an object class thread
* start by calling the object 5. thread class ()
*
*
* Comparative threads created in two ways.
* Development: preferences: implement Runnable way
* reason: the limitations of single inheritance is not the way to achieve 1 class
* 2. manner better suited to handle the case of multiple threads have shared data.
*
* Contact: public class Thread implements Runnable
same point *: Both approaches need to override run (), a logical statement will be executed in the thread run () in.
*
* /
// 1 creates a class that implements Runnable interface
class MThread the implements Runnable {

// implementation class 2 to implement the abstract method in Runnable:. RUN ()
@Override
public void RUN () {
for (int I = 0; i <100; i ++ ) {
IF (I% 2 == 0) {
System.out.println (Thread.currentThread () getName () + ":." + I);
}

}
}
}


public class ThreadTest1 {
public static void main (String [] args ) {
// create an object implementation class 3
MThread mThread new new MThread = ();
// this. 4 object passed as an argument to the Thread class constructor, creates an object of the Thread class
Thread t1 = new Thread (mThread) ;
t1.setName ( "thread 1");
// call the start through the object 5 thread class ():. ① ② threads started the current thread calls the run () -> call a run target of type Runnable ()
T1 .start ();

// then start a thread, even within 100 to traverse
the thread T2 = new new the thread (mThread);
t2.setName ( "thread 2");
t2.start ();
}

}

Guess you like

Origin www.cnblogs.com/wpy188/p/12094072.html