3.Java多线程的原理及使用
3.1 创建和启动线程
创建和启动线程,传统有两种方式:
方式一:继承Thread类;
-----------------------------------------------------------------
步骤:
1):定义一个类A继承于java.lang.Thread类.
2):在A类中覆盖Thread类中的run方法.
3):我们在run方法中编写需要执行的操作---->run方法里的,线程执行体.
4):在main方法(线程)中,创建线程对象,并启动线程.
创建线程类对象: A类 a = new A类();
调用线程对象的start方法: a.start();//启动一个线程
注意:千万不要调用run方法,如果调用run方法好比是对象调用方法,依然还是只有一个线程,并没有开启新的线程.
//播放音乐的线程
public class MusicThread extends java.lang.Thread {
public void run (){
for (int i = 0; i < 50; i++) {
System.out.println("播放音乐" + i);
}
}
}
//方式1:继承Thread类
public class ExtendsThreadDemo {
public static void main (String[] args) {
//主线程:运行游戏
for (int i = 0; i < 50; i++) {
System.out.println("打游戏" + i);
if(i == 10){
//创建线程对象,并启动线程
MusicThread t = new MusicThread();
t.start();//不能调用run方法
}
}
}
}
----------------------------------------------------------------
线程类(java.lang.Thread): Thread类和Thread的子类才能称之为线程类. 阅读API.
别忘了主线程(main方法运行,表示主线程).
方式二:实现Runnable接口;
//播放音乐的线程
public class MusicRunnableImpl implements java.lang.Runnable {
public void run (){
for (int i = 0; i < 50; i++) {
System.out.println("播放音乐" + i);
}
}
}
//方式2:实现Runnable接口
public class ImplementsRunnableDemo {
public static void main (String[] args) {
//主线程:运行游戏
for (int i = 0; i < 50; i++) {
System.out.println("打游戏" + i);
if(i == 10){
//创建线程对象,并启动线程
Runnable target = new MusicRunnableImpl();
Thread t = new Thread(target);
t.start();//不能调用run方法
}
}
}
}
使用匿名内部类来创建线程:
------------------------------------------------------------------------------------------
只适用于某一个类使用一次的情况.
使用接口形式的:
使用继承类形式的: