1、继承Thread类, 重写run方法,在main函数中,调用start方法。代码如下:
-
//播放音乐线程类
-
class MusicThread extends Thread {
-
public void run() {
-
for (int i = 0; i < 50; i++) {
-
System.out.println("播放音乐" + i);
-
}
-
}
-
}
-
-
//主线程类
-
public class ThreadDemo3 {
-
public static void main(String[] args) {
-
-
//启动播放音乐的线程
-
MusicThread thread1 = new MusicThread();
-
thread1.start();
-
-
//主线程
-
for (int i = 0; i < 50; i++) {
-
System.out.println("打游戏" + i);
-
}
-
}
-
}
2、实现Runnable接口,重写run方法,在main函数中,调用start方法。代码如下:
-
//1):定义一个类A实现于java.lang.Runnable接口,注意A类不是线程类.
-
class MusicImplements implements Runnable{
-
//2):在A类中覆盖Runnable接口中的run方法.
-
public void run() {
-
//3):在run方法中编写需要执行的操作
-
for(int i = 0; i < 50; i ++){
-
System.out.println("播放音乐"+i);
-
}
-
-
}
-
}
-
-
public class ImplementsRunnableDemo {
-
public static void main(String[] args) {
-
for(int j = 0; j < 50; j ++){
-
System.out.println("运行游戏"+j);
-
if(j == 10){
-
//4):在main方法(线程)中,创建线程对象,并启动线程
-
MusicImplements mi = new MusicImplements();
-
Thread t = new Thread(mi);
-
t.start();
-
}
-
}
-
}
-
-
}
3、实现Callable接口,重写call()方法,在main函数中调用start()方法。
import
java.util.concurrent.Callable;
public
class
ThreadImplementsCallable
implements
Callable<Integer> {
private
int
i;
@Override
public
Integer call()
throws
Exception {
for
(; i <
100; i++){
System.out.println(Thread.currentThread().getName() +
" "
+ i);
}
return
i;
}
}
import
java.util.concurrent.Callable;
import
java.util.concurrent.FutureTask;
public
class
Main {
public
static
void
main(String[] args) {
Callable<Integer> callable =
new
ThreadImplementsCallable();
FutureTask<Integer> futureTask =
new
FutureTask<>(callable);
for
(i =
0
; i <
100; i++){
System.out.println(Thread.currentThread().getName() +
" "
+ i);
if
(i ==
5) {
new
Thread(futureTask).start();
new
Thread(futureTask).start();
}
}
try
{
System.out.println(
"futureTask ruturn: "
+ futureTask.get());
}
catch
(Exception e) {
e.printStackTrace();
}
}
}