进程:执行中的程序(程序是静态的概念,进程是动态的概念)。
当使用第一种方式生成线程对象时,我们需要重写run方法,因为Thread类的run方法此时什么事情也不做,如下为Thread的run方法。
public void run() { if (target != null) { target.run(); } }
使用第二种方式生成线程对象:我们需要实现Runnable接口的run方法,然后使用new Thread(new MyThread())来生成线程对象(MyThread自定义的实现Runnable接口的类),这时线程对象的run方法会调用MyThread类的run方法,这样我们编写的run方法就执行了。
将我们希望运行的代码放入run方法中,然后通过start方法来启动线程,start方法首选为线程的执行准备好系统资源,然后再去调用run方法。当某个类继承Thread类后,该类就叫做一个线程类。
package com.test.thread; public class ThreadTest { public static void main(String[] args) { Thread1 thread1 = new Thread1(); thread1.start(); Thread2 thread2 = new Thread2(); thread2.start(); } } class Thread1 extends Thread{ public void run() { for (int i = 0; i < 100; i++) { System.out.println("hello world "+i); } } } class Thread2 extends Thread{ public void run() { for (int i = 0; i < 100; i++) { System.out.println("welcome "+i); } } }
对于单核CPU来说,某一时刻只能有一个线程在执行(微观串行),从宏观角度来看,多个线程在同时执行(宏观并行)。
对于双核或双核以上的CPU来说,可以做到真正的微观并行。
package com.test.thread; public class ThreadTest { public static void main(String[] args) { Thread myThread = new Thread(new MyThread()); myThread.start(); } } class MyThread implements Runnable{ public void run() { for(int i= 0;i<10;i++){ System.out.println("hello world "+i); } } }
或者这样写
package com.test.thread; public class ThreadTest { public static void main(String[] args) { Thread myThread = new Thread(new Runnable() { public void run() { for(int i = 0;i<10;i++){ System.out.println("hello world "+i); } } }); myThread.start(); } }
当生成一个线程时,如果没有为其设定名称,那么Thread类将会为此线程设定一个默认的名称,使用如下形式:
Thread-number,该number是自动增加的,并被所有的Thread对象共享(因为它是static成员变量)。也可以使用Thread(String name)构造函数来设置名称,或使用setName(String name)来设置名称。