Java基础回顾 : 线程的实现方式

总结 :关于Thread类与Runnable接口的区别?(多线程两种实现方式的区别)


        ├ . Thread类是Runnalbe接口的子类 ;


        ├ . 如果要想实现多线程,那么必须要有线程主体类,主体类可以继承Thread类或实现Runnable接口,但是实现接口可以有效的避免单继承局限 ;


        ├ . 利用Runnable实现的多线程类,可以更加方便的表示出数据共享的概念 . 


示例 : 通过实现Runnalbe接口来实现多线程

package example;

class MyThread implements Runnable{
	private String title;
	public MyThread (String title){
		this.title = title;
	}
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			System.out.println("线程:" + this.title + " ,i = " + i);
		}
	}
}

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("A");
		MyThread mt2 = new MyThread("B");
		MyThread mt3 = new MyThread("C");
		
		Thread t1 = new Thread(mt1);
		Thread t2 = new Thread(mt2);
		Thread t3 = new Thread(mt3);
		
		t1.start();
		t2.start();
		t3.start();
	}
	
}


示例 : 通过继承Thread类来实现多线程

package example;

class MyThread extends Thread{
	private String title;
	public MyThread (String title){
		this.title = title;
	}
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			System.out.println("线程:" + this.title + " ,i = " + i);
		}
	}
}

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("A");
		MyThread mt2 = new MyThread("B");
		MyThread mt3 = new MyThread("C");
		
		mt1.start();
		mt2.start();
		mt3.start();
	}
	
}


示例 : 通过实现Runnable接口来实现数据共享

package example;

class MyThread implements Runnable{
	private int ticket = 10;
	@Override
	public void run() {
		for(int i=0;i<50;i++){
			if(ticket > 0){
				System.out.println(Thread.currentThread().getName() + "卖票:" + this.ticket --);
			}
		}
	}
}

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt = new MyThread(); 
		
		//三个线程,共享主体线程mt
		Thread t1 = new Thread(mt,"A");
		Thread t2 = new Thread(mt,"B");
		Thread t3 = new Thread(mt,"C");
		
		t1.start();
		t2.start();
		t3.start();
	}
	
}



示例 : 通过继承Thread类来实现数据共享

package example;

class MyThread extends Thread{
	private int ticket = 10;
	@Override
	public void run() {
		for(int i=0;i<50;i++){
			if(ticket > 0){
				System.out.println(Thread.currentThread().getName() + "卖票:" + this.ticket --);
			}
		}
	}
}

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt = new MyThread(); //Thread类实现了Runnable接口
		
		//三个线程,共享主体线程mt
		Thread t1 = new Thread(mt,"A");
		Thread t2 = new Thread(mt,"B");
		Thread t3 = new Thread(mt,"C");
		
		t1.start();
		t2.start();
		t3.start();
	}
	
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值