您的位置:首页 > 编程语言 > Java开发

创建线程的两种传统方式

2017-08-17 18:03 351 查看
首先,了解下线程。
Thread  thread = new Thread();
thread.start();                            //线程执行的代码是thread类里的run方法,如果run方法为空,则什么都不干


让我们看看run方法都干了些什么
public void run() {
if (target != null) {
target.run();
}
}


结论:如果要执行自己的代码,则要“改写run方法”

方法一:继承Thread,子类重写run方法(匿名内部类)
Thread  thread = new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);                //500毫秒=0.5秒
}  catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());       //打印当前线程的名字
}
}
};
thread.start();


方法二:通过构造方法传一个Runable对象,因为target是一个Runable对象
(第二种方式更加体现Java面向对象的特点)
Thread  thread2 = new Thread(new Runnable(){
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);                //500毫秒=0.5秒
}  catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());       //打印当前线程的名字
}
}
});
thread2.start();


匿名内部类对象的构造方法如何调用父类的非默认构造方法

定义一个接口A
interface A{
public int add(int b,int c);
}


在main方法中加上
new A(){
/*这里的new A() 就是调用构造方法 如有有参数的就直接写参数就行了 new A("aa") 着样就行
匿名内部类不能重新定义新的构造方法*/
public int add(int b, int c) {
return b+c;
}
};


关于匿名内部类:http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html
这是网上关于匿名内部类的总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程