线程:每一个任务称为一个线程,线程不能独立的存在,它必须是进程的一部分
单线程:般常见的Java应用程序都是单线程的,比如运行helloworld的程序时,会启动jvm进程,然后运行main方法产生线程,main方法也被称为主线程。
多线程:同时运行一个以上线程的程序称为多线程程序,多线程能满足程序员编写高效率的程序来达到充分利用 CPU 的目的。
单线程代码例子:
public class SingleThread {public static void main(String[] args){Thread thread = Thread.currentThread(); //获取当前运行的线程对象thread.setName("单线程"); //线程重命名System.out.println(thread.getName()+"正在运行");for(int i=0;i<10;i++){System.out.println("线程正在休眠:"+i);try {thread.sleep(1000); //线程休眠,延迟一秒} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("线程出错");}}}}多线程代码例子:
注意:多线程有两种实现方式,一种是继承Thread类,另一种是实现Runnable接口。
继承Thread类实现多线程
public class TestThread {public static void main(String[] args){ Thread t1 = new ExtendThread("t1",1000); //使用上转对象创建线程,并构造线程名字和线程休眠时间 Thread t2 = new ExtendThread("t2",2000); Thread t3 = new ExtendThread("t3",3000); t1.start(); //启动线程并调用run方法 t2.start(); t3.start();}}class ExtendThread extends Thread{ //继承Thread的类String name;int time;public ExtendThread(String name, int time) { //构造线程名字和休眠时间this.name=name;this.time=time;}public void run(){ //重写Thread类的run方法try{sleep(time); //所有线程加入休眠}catch(InterruptedExceptione){e.printStackTrace();System.out.println("线程中断异常");}System.out.println("名称为:"+name+",线程休眠:"+time+"毫秒"); }}实现Runnable接口的多线程
public class RunnableThread {public static void main(String[] args){Runnable r1=new ImplRunnable("r1",1000); //Runnable接口必须依托Thread类才能创建线程Thread t1=new Thread(r1); //Runnable并不能调用start()方法,因为不是线程,所以要用Thread类加入线程Runnable r2=new ImplRunnable("r2",2000);Thread t2=new Thread(r2);Runnable r3=new ImplRunnable("r3",3000);Thread t3=new Thread(r3);t1.start(); //启动线程并调用run方法t2.start();t3.start();}}class ImplRunnable implements Runnable{ //继承Runnable接口的类String name;int time;public ImplRunnable(String name, int time) { //构造线程名字和休眠时间this.name = name;this.time = time;}@Overridepublic void run() { //实现Runnable的run方法try{Thread.sleep(time); //所有线程加入休眠}catch(InterruptedException e){e.printStackTrace();System.out.println("线程中断异常");}System.out.println("名称为:"+name+",线程休眠:"+time+"毫秒");}}说明:Thread类实际上也是实现了Runnable接口的类。
实现Runnable接口比继承Thread类所具有的优势