欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

实例分析Java单线程与多线程

时间:2021-09-25 08:18:25|栏目:JAVA代码|点击:

线程:每一个任务称为一个线程,线程不能独立的存在,它必须是进程的一部分

单线程:般常见的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 block
				e.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;
	}

	@Override
	public 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类所具有的优势

上一篇:Java代码注释规范(动力节点整理)

栏    目:JAVA代码

下一篇:springBoot定时任务处理类的实现代码

本文标题:实例分析Java单线程与多线程

本文地址:http://www.codeinn.net/misctech/177322.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有