进程是一个静态的概念,线程是一个进程里面的不同的执行路径,一个cpu实际上每个时间点只能执行一个线程
- (继承,重写,父类引用指向子类对象)
package com.site.line; public class TestLine { public static void main(String[] args) { m1(); } public static void m1(){ m2(); m3(); } public static void m2(){}; public static void m3(){}; }
创建线程:
-
package com.site.line; public class StartLine { public static void main(String[] args) { Runner1 r = new Runner1(); Thread t = new Thread(r); t.start();//调用start方法,线程启动 for (int i=0;i<100;i++){ System.out.println("Main Thread:----"+i); } } } //实现Runner接口 class Runner1 implements Runnable{ @Override //实现run()方法 public void run() { for (int i = 0; i <100 ; i++) { System.out.println("Runner1:"+i); } } }
线程启动方法一:重写Runnable接口,实例化Thread对象再启动线程
-
package zrm; public class Threadl { /*thread*/ public static void main(String[] args) { Runner1 runner1 = new Runner1(); Thread thread = new Thread(runner1); thread.start(); for (int ii = 0; ii < 1000; ii++) { System.out.println("this is the main thread:" + ii); } } } /*重写Runnable接口*/ class Runner1 implements Runnable { @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println("this is runnale's run():" + i); } } }
方法二:直接用一个子类继承Thread类,并且重写Thread的run()方法
-
package com.site.line; public class StartLine { public static void main(String[] args) { Runner1 r = new Runner1(); r.start();//直接使用 //Thread t = new Thread(r);//这里就不需要在new一个新的Thread对象 //t.start(); for (int i=0;i<100;i++){ System.out.println("Main Thread:----"+i); } } } //实现Runner接口 //class Runner1 implements Runnable{ class Runner1 extends Thread{ //实现run()方法 public void run() { for (int i = 0; i <100 ; i++) { System.out.println("Runner1:"+i); } } }
线程的状态转换:
- 线程的一些常用方法;