java 多线程

本文详细介绍了Java中创建线程的三种方法:继承Thread类、实现Runnable接口以及实现Callable接口。通过实例代码展示了每种方法的用法,包括启动线程、设置线程名以及打印线程执行信息。对于Callable接口,还演示了如何获取返回值。这些内容有助于理解Java并发编程的基础知识。
摘要由CSDN通过智能技术生成

方法一:

/*

  • 继承Thread类,重写run
    */

package com.fatiaoyu;

public class ThreadTest1 {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName(“线程1”);

	MyThread thread2 = new MyThread();
	thread2.setName("线程2");

	thread1.start();
	thread2.start();
}

}

class MyThread extends Thread {

public void run() {
	for (int i = 0; i < 100; i++) {
		System.out.println(Thread.currentThread().getName() + ",i=" + i);
	}
}

}

方法二:实现runnable接口,重写run方法
package com.fatiaoyu;

public class Runnable_test {

public static void main(String[] args) {
	MyThread myThread1 = new MyThread();
	Thread thread1 = new Thread(myThread1);
	thread1.setName("线程1");

	MyThread myThread2 = new MyThread();
	Thread thread2 = new Thread(myThread2);
	thread2.setName("线程2");

	thread1.start();
	thread2.start();
}

}

class MyThread2 implements Runnable {
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + “,i=” + i);
}
}
}

在这里插入图片描述

方法三:实现callable接口

package com.fatiaoyu;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Callable_test {
public static void main(String[] args) throws Exception {

	MyThread3 mt = new MyThread3();
	MyThread3 mt2 = new MyThread3();
	FutureTask<String> task = new FutureTask<String>(mt);
	FutureTask<String> task2 = new FutureTask<String>(mt2);

	Thread thread1 = new Thread(task);
	Thread thread2 = new Thread(task2);

	thread1.start();
	thread2.start();

	System.out.println(task.get());
	System.out.println(task2.get());
}

}

class MyThread3 implements Callable {

public String call() {
	for (int i = 1; i < 100; i++) {
		System.out.println(Thread.currentThread().getName() + ",i=" + i);
	}
	return "执行成功";
}

}

打印结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值