日期:2017/11/10

      Java常用的多线程方法有两个:

               (1)继承Thread类+重写run方法,在mian()中用start()方法调用启动;

代码例子如下:


package com.thread;

public class MyThread extends Thread{
private String name;

public MyThread(String name){
this.name = name;
}

public void run(){
for (int i=10; i<1010; i++){
System.out.println(name +": "+i);
}
// super.run();
}

}
package com.thread;


public class ThreadTest {


public static void main(String[] args) {
MyThread thread = new MyThread("Thread Test One");
MyThread threadtwo = new MyThread("Thread Test Two");
//线程的启动不是通过run方法(调用)
//thread.run();
thread.start();
threadtwo.start();
System.out.println("**********");

//another way to realize Thread
MyRunnable myrunnable1 = new MyRunnable("A");
MyRunnable myrunnable2 = new MyRunnable("B");
Thread t1 = new Thread(myrunnable1);
Thread t2 = new Thread(myrunnable2);
t1.start();
t2.start();
}


}




mian()中新建Thread引用并使用start()方法调用启动;

代码例子:


package com.thread;

class ThreadDemo implements Runnable{
private String name;
public ThreadDemo(String name){
this.name = name;
}
public void run() {
for (int i = 0; i<50; i++){
try{
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+": "+i);
}catch(InterruptedException e){
e.printStackTrace();
}
}

}

}

public class ThreadTestThree {

public static void main(String[] args) {
//使用匿名对象,创建线程更加方便
Thread t1 = new Thread(new ThreadDemo("A"),"A");
Thread t2 = new Thread(new ThreadDemo("B"),"B");
Thread t3 = new Thread(new ThreadDemo("C"),"C");
// t1.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();

}

}


   

 PS:一般来说,使用Runnable接口实现的方法更加灵活,因为接口能够多个实现,更加易于满足业务增长的需求;但是使用继承的方法,则是不能扩展更多的功能了。