1.Thread类
定义线程类
class MyThread extends Thread { // 线程的主体类
private String title; // 成员属性
public MyThread(String title) { // 属性初始化
this.title = title;
}
@Override
public void run() { // 【方法覆写】线程方法
for (int x = 0; x < 10; x++) {
System.out.println(this.title + "运行,x = " + x);
}
}
}
Thread实现多线程
public class ThreadDemo {
public static void main(String[] args) {
new MyThread("线程A").start() ; // 实例化线程对象并启动
new MyThread("线程B").start() ; // 实例化线程对象并启动
new MyThread("线程C").start() ; // 实例化线程对象并启动
}
}
2.Runnable接口实现多线程
class MyThread implements Runnable { // 线程的主体类
private String title; // 成员属性
public MyThread(String title) { // 属性初始化
this.title = title;
}
@Override
public void run() { // 【方法覆写】线程方法
for (int x = 0; x < 10; x++) {
System.out.println(this.title + "运行,x = " + x);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Thread threadA = new Thread(new MyThread("线程对象A")) ;
Thread threadB = new Thread(new MyThread("线程对象B")) ;
Thread threadC = new Thread(new MyThread("线程对象C")) ;
threadA.start(); // 启动多线程
threadB.start(); // 启动多线程
threadC.start(); // 启动多线程
}
}
通过Lambda表达式定义线程方法体
package cn.mldn.demo;
public class ThreadDemo {
public static void main(String[] args) {
for (int x = 0; x < 3; x++) {
String title = "线程对象-" + x;
new Thread(() -> { // Lambda实现线程体
for (int y = 0; y < 10; y++) {
System.out.println(title + "运行,y = " + y);
}
}).start(); // 启动线程对象
}
}
}
并发资源访问
package cn.mldn.demo;
class MyThread implements Runnable { // 线程的主体类
private int ticket = 5; // 定义总票数
@Override
public void run() { // 线程的主体方法
for (int x = 0; x < 100; x++) { // 进行100次的卖票处理
if (this.ticket > 0) { // 有剩余票
System.out.println("卖票,ticket = " + this.ticket--);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread mt = new MyThread(); // 定义资源对象
new Thread(mt).start(); // 第一个线程启动
new Thread(mt).start(); // 第二个线程启动
new Thread(mt).start(); // 第三个线程启动
}
}
3.Callable接口实现多线程
class MyThread implements Callable<String> { // 定义线程主体类
@Override
public String call() throws Exception { // 线程执行方法
for (int x = 0; x < 10; x++) {
System.out.println("********* 线程执行、x = " + x);
}
return "www.mldn.cn"; // 返回结果
}
}
public class ThreadDemo {
public static void main(String[] args) throws Exception {
// 将Callable实例包装在FutureTask类之中,这样可以就可以与Runnable接口关联
FutureTask<String> task = new FutureTask<>(new MyThread()) ;
new Thread(task).start(); // 线程启动
System.out.println("【线程返回数据】" + task.get()); // 获取返回结果
}
}