您的位置:首页 > 其它

张孝祥[致敬]-多线程学习第01课 传统线程的创建

2016-11-02 23:25 363 查看
本人地址:http://blog.csdn.net/hblfyla/article/details/53014756

什么是线程?

        线程就是程序执行的不同分支

传统创建线程的两种方式
    1.继承Thread类,本次采用面向对象的写法,所有代码都封装在一个对象里面

代码:

package org.yla.zxx.day01;
/**
* 复习创建线程的方式
* @author yangluan
* 2016年11月2日下午11:05:23
*/
public class TraditionalThreadDemo01 {
public static void main(String[] args) {
//继承Thread类
Thread t = new Thread(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread->1: "+Thread.currentThread().getName());
System.out.println("thread->2: "+this.getName());
}
};
};

t.start();
}
}

运行:

thread->1: Thread-0
thread->2: Thread-0
thread->1: Thread-0
thread->2: Thread-0
thread->1: Thread-0
thread->2: Thread-0
thread->1: Thread-0
thread->2: Thread-0


 2.实现Runnable接口,本次采用面向对象的写法,所有代码都封装在一个对象里面
代码:
package org.yla.zxx.day01;
/**
* 传统创建线程复习
* @author yangluan
* 2016年11月2日下午11:09:44
*/
public class TraditionalThreadDemo02 {
public static void main(String[] args) {
//实现Runnalable接口
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable->1: "+Thread.currentThread().getName());
}

}
});

t.start();
}
}

运行:

Runnable->1: Thread-0
Runnable->1: Thread-0
Runnable->1: Thread-0
Runnable->1: Thread-0
........


思考题:如下代码写法会运行什么结果?
代码:
package org.yla.zxx.day01;
/**
* 传统创建线程复习
* @author yangluan
* 2016年11月2日下午11:09:44
*/
public class TraditionalThreadDemo03 {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable: "+Thread.currentThread().getName());
}

}
}){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread: "+Thread.currentThread().getName());
}
};
}.start();
}

//new Thread(new Runnable(){run()}){run()}.start();
//子类对象覆写父类对象方法,所以调用的是子类对象的方法
}

运行:

thread: Thread-0
thread: Thread-0
thread: Thread-0
thread: Thread-0
thread: Thread-0
thread: Thread-0
.........

本人地址:http://blog.csdn.net/hblfyla/article/details/53014756
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: