实现线程的两种方式

一:线程

简单的来说:一个应用程序可以看成一个进程,比如QQ,PPS应用都是进程(当然,一个应用也可能有多个进程)。然后,在QQ应用中,可能有多个方法,比如,发送信息,接受信息,缓冲,播放,这些每一个具体的方法,都可以作为一个线程存在和使用。

二:Thread 类

继承Thread类:

class 类名称 extends Thread{		//继承Thread类
	属性 ……;
	方法 ……;
	public void run(){			//覆写Thread类的run()方法
		线程主体……;
	}
}
但是在调用这个run()方法的时候,使用的是start()方法,这样,线程才会交替进行。

范例1:

package haizhu.com;

class MyThread extends Thread{
	private String name;
	public MyThread(String name){						//覆写构造方法
		this.name = name;
	}
	public void run(){									

//覆写run()方法
		for(int i=0;i<10;i++){
			System.out.println(this.name + i + "\t运行中");
		}
	}
}

public class MyThreadDemo {
	public static void main(String args[]){
		MyThread my1 = new MyThread("线程 A ");			//创建对象线程A
		MyThread my2 = new MyThread("线程 B ");			//创建对象线程B
		my1.start();										

//使用start启动线程
		my2.start();
	}
}
可能的结果之一:

线程 A 0	运行中
线程 B 0	运行中
线程 B 1	运行中
线程 B 2	运行中
线程 A 1	运行中
线程 A 2	运行中
线程 B 3	运行中
线程 B 4	运行中
线程 B 5	运行中
线程 A 3	运行中
线程 B 6	运行中
线程 B 7	运行中
线程 B 8	运行中
线程 A 4	运行中
线程 A 5	运行中
线程 A 6	运行中
线程 A 7	运行中
线程 A 8	运行中
线程 A 9	运行中
线程 B 9	运行中


三:Runnable 接口
实现Runnable接口
class 类名称 implements Thread{			//实现Runnable接口
	属性 ……;
	方法 ……;
	public void run(){			//覆写Thread类的run()方法
		线程主体……;
	}
}
范例2:

package haizhu.com;

class MyThread implements Runnable{
	private String name;
	public MyThread(String name){						//覆写构造方法
		this.name = name;
	}
	public void run(){									

//覆写run()方法
		for(int i=0;i<10;i++){
			System.out.println(this.name + i + "\t运行中");
		}
	}
}

public class MyThreadDemo {
	public static void main(String args[]){
		MyThread my1 = new MyThread("线程 A ");			//创建对象线程A
		MyThread my2 = new MyThread("线程 B ");			//创建对象线程B
		Thread t1 = new Thread(my1);					//虽然实现

Runnable接口,但是启动线程的操作
		Thread t2 = new Thread(my2);					//还是依靠Thread

类的实例进行调用Thread类的start()方法
		t1.start();
		t2.start();
	}
}
通过实现Runnable接口的方式进行多线程,但是启动线程的时候还是依靠Thread类的对象来实现。
在Thread类中提供了两个方法:public Thread(Runnable target) 和 public Thread(Runnable target, String name),这两个方法都可以接受Runnable的子类实例对象,所以依靠这个启动多线程。

四:Thread 和 Runnable 区别

使用Runnable可以实现资源的共享,但是如果继承Thread类则不行。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值