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

原文链接:https://www.idaobin.com/archives/807.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

40 ÷ 4 =