在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。
线程调度过程如下:
1.继承Thread类
1.1继承Thread类,
1.2重写run()方法。run()方法中的是线程体。
一旦继承Thread类,便不能再继承其他类。
class test_thread extends Thread { public test_thread() { } public test_thread(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { test_thread t1=new test_thread("A"); test_thread t2=new test_thread("B"); t1.run(); t2.run(); } private String name;}
2.实现Runable接口
2.1实现Runable接口中的run()方法
2.2初始化Thread类。
2.3启动线程,传递Runable接口。
class test_run implements Runnable { public test_run() { } public test_run(String name) { this.name = name; } public void test_run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { test_run r1=new test_run("线程A"); Thread test1= new Thread(r1); test_run r2=new test_run("线程B"); Thread test2=new Thread(r2); test1.start(); test2.start(); } private String name;}
(********************************************
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。
*********************************************)
3.线程控制
3.1Thread.sleep();
3.2Thread.yeild();
该方法自动让出CPU,使得线程之间自由抢占CPU,线程优先级越大,抢占CPU的可能性越大。