创建线程有两种方式:
1.继承Thread
2.实现Runnable接口
举例:同时听音乐玩游戏
package dms.java.base.thread;
/**
* 创建启动线程,方式一继承Thread类
* @author BrightSt
*
*/
public class ThreadDemo{
/**
* 主线程
* @param args
*/
public static void main(String[] args) {
Thread2 t2 = new Thread2();
t2.start(); // 注意:千万不能直接掉用run方法,如果这样做了,就是普通的对象调用方法了,不是启动线程。调用start启动线程后,内部会调用run方法执行
Thread1 t1 = new Thread1();
t1.start();
}
}
/**
* 玩游戏线程
* @author BrightSt
*
*/
class Thread1 extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
System.out.println("play game");
}
}
}
/**
* 听音乐线程
* @author BrightSt
*
*/
class Thread2 extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
System.out.println("listen music");
}
}
}
控制台输出部分如下:(发现交替执行了)
listen music
listen music
listen music
listen music
play game
play game
play game
play game
play game
play game
play game
play game
play game
play game
play game
play game
play game
listen music
listen music
listen music
listen music
实现Runnable接口实现线程创建启动:
package dms.java.base.thread;
/**
* 创建启动线程方法二,实现Runnable接口
* @author BrightSt
*
*/
public class ThreadDemo2 {
/**
* 主线程
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new Music());
Thread t2 = new Thread(new Game());
t1.start();
t2.start();
}
}
class Music implements Runnable{
@Override
public void run() {
for (int i=0;i<50;i++) {
System.out.println("listen music "+i);
}
}
}
class Game implements Runnable{
@Override
public void run() {
for (int i=0;i<50;i++) {
System.out.println("play game "+i);
}
}
}
控制台输出部分:
play game 32
play game 33
play game 34
play game 35
listen music 13
listen music 14
play game 36
play game 37
play game 38
listen music 15
play game 39
play game 40
play game 41
play game 42
play game 43
play game 44
play game 45
play game 46
play game 47
listen music 16
listen music 17
listen music 18