Java多线程实现——Runnable和Thread的区别

本文通过两个示例对比了在Java中使用Runnable接口和继承Thread类实现多线程的区别,重点分析了共享变量num在不同实现方式下的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

synchronized ThreadLocal

转载:https://blog.csdn.net/shakespeare001/article/details/51321498

1.实现Runnable:

package com;


public class HelloWorld implements Runnable{

	private int num=0;
	public static void main(String[] args){
	
			HelloWorld hw=new HelloWorld();
			new Thread(hw).start();
			new Thread(hw).run();
		
	}

	public void run() {
		System.out.println("开始运行");
		for(int i=0;i<5;i++) {
			System.out.println(num++);
		}
	}	
	
	
}

运行结果:我尝试运行了多次,大概有一下这两种结果:

package com;


public class HelloWorld implements Runnable{

	private int num=0;
	public static void main(String[] args){
	
			HelloWorld hw=new HelloWorld();
			new Thread(hw).start();
			new Thread(hw).start();
		
	}

	public void run() {
		System.out.println("开始运行");
		for(int i=0;i<5;i++) {
			System.out.println(num++);
		}
	}	
	
	
}

运行结果:

有以下几种:

 

2.继承 Thread

package com;


public class HelloWorld extends Thread{

	private int num=0;
	public static void main(String[] args){
	
			new HelloWorld().start();
			new HelloWorld().start();
		
	}

	public void run() {
		System.out.println("开始运行");
		for(int i=0;i<5;i++) {
			System.out.println(num++);
		}
	}	
	
	
}

运行结果:

分析 :继承(extends)自Thread来实现多线程时,每个线程都独立拥有一份自己的变量,各个线程之间不能实现资源的共享;而实现(implements)Runnable来实现多线程时,可以实现各个线程之间资源的共享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值