概述
自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取:
1 Java线程原理和两种实现方式
1.1 java线程原理和源码解析
线程是为了实现并发运行,java线程实现有两种方式。一种是继承 Thread 类,另一种就是实现 Runnable 接口,实现Runnable接口的run函数。Thread类实际上也是实现了runnable接口,并且在Thread类中实现了Runnable接口的run函数,只是这个run函数是一个Override函数,继承Thread的类要么重写这个run函数,要入以入参的形式传入Runnable 接口实现类对象,也就是下面的target对象,传入了Runable接口实现类对象target,则target不为null,执行target的run方法,如果没有传入target,则target为空,这是需要重写Tread的run函数。总而言之,就是要实现run方法,要么重写,要么入参传入。
Public classThread implementsRunnable {
……
@Override
public voidrun() {
if(target!= null) {
target.run();
}
}
……
Private Runnable target;
//构造函数1,需要重写run函数
publicThread(String name) {
init(null, null, name, 0);
}
//构造函数2,需要以入参传入的Runnable接口对象
public Thread(Runnable target,String name){
init(null,target,name,0);
}
//初始化函数
private void init(ThreadGroup g,Runnable target,String name,long stackSize){
...
this.target=target;
}
……
}
1.2 实现Runnable接口实现run方法
Runnable接口定义
interfaceRunnable {
/**
* When an object implementing
interface Runnable
is used
* to create a thread, starting the
thread causes the object's
* run
method to be called in that
separately executing
* thread.
*
* The general contract of the method
run
is that it may
* take any action whatsoever.
*
* @seejava.lang.Thread#run()
*/public abstract voidrun();
}
classMyThread implementsRunnable{ //实现Runnable接口,作为线程的实现类privateString name; //表示线程的名称publicMyThread(String name){
this.name= name ; //通过构造方法配置name属性}
public voidrun(){ //覆写run()方法,作为线程 的操作主体for(inti=0;i<10;i++){
System.out.println(name+ "运行,i = "+ i) ;
}
}
public static voidmain(String args[]){
MyThread mt1 = newMyThread("线程A ") ; //实例化对象MyThread mt2 = newMyThread("线程B ") ; //实例化对象Thread t1 = newThread(mt1) ; //实例化Thread类对象Thread t2 = newThread(mt2) ; //实例化Thread类对象t1.start() ; //启动多线程t2.start() ; //启动多线程}
};
运行结果为:
线程B 运行,i = 0
线程B 运行,i = 1
线程B 运行,i = 2
线程B 运行,i = 3
线程B 运行,i = 4
线程B 运行,i = 5
线程B 运行,i = 6
线程B 运行,i = 7
线程B 运行,i = 8
线程B 运行,i = 9
线程A 运行,i = 0
线程A 运行,i = 1
线程A 运行,i = 2
线程A 运行,i = 3
线程A 运行,i = 4
线程A 运行,i = 5
线程A 运行,i = 6
线程A 运行,i = 7
线程A 运行,i = 8
线程A 运行,i = 9
1.3 继承Thread类重写run方法
class MyThread extends Thread{ // 继承Thread类,作为线程的实现类
private String name ; // 表示线程的名称
public MyThread(String name){
this.name = name ; // 通过构造方法配置name属性
}
public void run(){ // 覆写run()方法,作为线程 的操作主体
for(int i=0;i<10;i++){
System.out.println(name + "运行,i = " + i) ;
}
}
};
public class ThreadDemo02{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A ") ; // 实例化对象
MyThread mt2 = new MyThread("线程B ") ; // 实例化对象
mt1.start() ; // 调用线程主体
mt2.start() ; // 调用线程主体
}
};
线程A 运行,i = 0
线程B 运行,i = 0
线程B 运行,i = 1
线程B 运行,i = 2
线程B 运行,i = 3
线程B 运行,i = 4
线程B 运行,i = 5
线程B 运行,i = 6
线程B 运行,i = 7
线程B 运行,i = 8
线程B 运行,i = 9
线程A 运行,i = 1
线程A 运行,i = 2
线程A 运行,i = 3
线程A 运行,i = 4
线程A 运行,i = 5
线程A 运行,i = 6
线程A 运行,i = 7
线程A 运行,i = 8
线程A 运行,i = 9
最后
以上就是如意飞机为你收集整理的JAVA中初始化线程的两种方法_1.java线程的源码解析和两种线程创建方法的全部内容,希望文章能够帮你解决JAVA中初始化线程的两种方法_1.java线程的源码解析和两种线程创建方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复