java中实现多线程的几种方式(简单实现)

时间:2023-03-09 02:51:28
java中实现多线程的几种方式(简单实现)

一、以下只是简单的实现多线程

1:继承Thread

2:实现 Runnable

3:实现callable

如果需要返回值使用callable,如果不需要返回最好使用runnable,因为继承只能单继承,所以不推荐使用Thread。

具体代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class Thread_Test {
    private class Thread1 extends Thread{
@Override
public void run() {
super.run();
System.out.println("执行了Thread的Run方法");
}
} private class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("执行了Runnable的Run方法");
}
} private class Thread3 implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("执行了Runnable的Run方法");
Thread.sleep(5000);    //让线程休眠5s,测试返回值
return "I am callable";
}
} @Test
public void testThread() throws Exception{
Thread1 t1 = new Thread1();
new Thread(t1).start(); Thread2 t2 = new Thread2();
new Thread(t2).start(); Thread3 t3 = new Thread3();
FutureTask<String> task = new FutureTask<String>(t3);
new Thread(task).start();
System.out.println(task.get());          //是异步获取的值,等待程序执行完
}
} 执行结果

java中实现多线程的几种方式(简单实现)

二、停止线程的方法

suspend()、resume()、stop() ,不建议使用,这种是强制关闭线程,如果有锁可能不会释放。

建议使用interrupt()方法停止线程。

interrupt:中断一个线程。不是强行的中断,只是添加了一个中断标志位true。

interrupted:判定当前线程是否处于中断状态。

static的 isInterrupted:判定当前线程是否处于中断状态。他会把中断的标志位给位false。

代码:public class EndThread {

    private static class UseThread extends Thread{
@Override
public void run() {
String name = Thread.currentThread().getName();
while(!isInterrupted()){  //当中断标识位位true,就跳出循环。
System.out.println(name+"is run");
}
       System.out.println(name + "is flag "+isInterrupted()); //当前的标识位为true
       interrupted(); //interrupted把中断标识位设置为false。
       System.out.println(name + "is flag "+isInterrupted()); //当前的标识位为false
      }
  }
    public static void main(String[] args) throws Exception {
Thread u = new UseThread();
u.start();
Thread.sleep(1000);
u.interrupt(); //告诉程序要中断了,设置中断标志位。
}
} 运行结果

  Thread-0is run
  Thread-0is run
  Thread-0is flag true
  Thread-0is flag false