java中实现多线程之实现runnable接口
1.处理业务代码
//根据传参打印对应的名字
private void printName(String name) throws Exception{
System.out.println(name);
}
2.创建内部类实现Runnable接口
private class PrintName implements Runnable{
private String name;
public PrintName(String name){
this.name = name;
}
//Runnable接口中的抽象方法
@Override
public void run(){
try {
printName(name);
}catch (Exception e){
System.out.println(e);
}
}
}
- 创建线程对象并执行线程
private void createThead() throws Exception {
String name = "hello world";
Thread thread = new Thread(new PrintName(name));
thread.start();
}
现在附上全部代码:
package com.ieou.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class Demo1Controller {
/** java 多线程 异步实现demo */
//第一步 处理业务代码
//根据传参打印对应的名字
private void printName(String name) throws Exception{
System.out.println(name);
}
//创建内部类实现Runnable接口
private class PrintName implements Runnable{
private String name;
public PrintName(String name){
this.name = name;
}
//Runnable接口中的抽象方法
@Override
public void run(){
try {
printName(name);
}catch (Exception e){
System.out.println(e);
}
}
}
//第三部 创建线程对象
private void createThead() throws Exception {
String name = "hello world";
Thread thread = new Thread(new PrintName(name));
thread.start();
}
@GetMapping("/name")
public String findName() throws Exception{
System.out.println("name1");
createThead();
System.out.println("name3");
return "1";
}