//创建多线程方式2:实现Runnable接口,重写run方法,执行线程需放入ruannable接口实现类
public class TestThread2 implements Runnable {
@Override
public void run() {
//run方法的重写
for (int i = 0; i < 10; i++) {
System.out.println("run方法的打印次数" + i);
}
}
public static void main(String[] args) {
//创建runnable接口实现类对象并开始线程
new Thread(new TestThread2()).start();
for (int i = 0; i < 10; i++) {
System.out.println("main主方法的打印次数" + i);
}
}
}
范例:多线程会出现并发状态。
public class TestThread3 implements Runnable {
/**
* 苹果余额
*/
private static int number =99;
@Override
public void run() {
while(true){
if(number <= 0){
System.out.println("售罄");
break;
}
//睡觉、延时
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取线程名字
System.out.println(Thread.currentThread().getName() + "买的最后第" + number-- + "个苹果");
}
}
public static void main(String[] args) {
//创建runnable接口实现类
TestThread3 testThread3 = new TestThread3();
new Thread(testThread3,"张三").start();
new Thread(testThread3,"李四").start();
new Thread(testThread3,"王五").start();
}
}
3.Java多线程--Callable接口实现(了解)
步骤:创建多线程方式3:实现Callable接口,重写call方法
//创建多线程方式3:实现Callable接口,重写call方法
public class TestCallable implements Callable {
@Override
public Object call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "call方法打印的次数" + i);
}
return null;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testCallable = new TestCallable();
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(1);
//提交执行
Future submit = executorService.submit(testCallable);
for (int i = 0; i < 10; i++) {
System.out.println("main主方法的打印次数" + i);
}
//获取结果
submit.get();
//关闭服务
executorService.shutdown();
}
}