开启一个线程的方法?

Posted top啦它

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开启一个线程的方法?相关的知识,希望对你有一定的参考价值。

public class MyTest4 extends Thread
    @Override
    public void run() 
        System.out.println("start");
        try 
            Thread.sleep(10000);
         catch (InterruptedException e) 
            e.printStackTrace();
        
        System.out.println("end");
    

    public static void main(String[] args) 
        MyTest4 myTest41 = new MyTest4();
        MyTest4 myTest42 = new MyTest4();
        myTest41.start();
        myTest42.start();
    

public class MyTest5 
    public static void main(String[] args) 
        Thread thread1 = new Thread(new TestRun());
        thread1.setName("thread1");
        Thread thread2 = new Thread(new TestRun());
        thread2.setName("thread2");
        thread1.start();
        thread2.start();

    



class TestRun implements Runnable
    @Override
    public void run() 
        System.out.println("start");
        try 
            Thread.sleep(1000);
         catch (InterruptedException e) 
            e.printStackTrace();
        
        System.out.println(Thread.currentThread().getName());
        System.out.println("end");
    

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

public class MyTest6 
    public static void main(String[] args) throws ExecutionException, InterruptedException 
        TestCall testCall1 = new TestCall();
        TestCall testCall2 = new TestCall();
        FutureTask<String> futureTask1 = new FutureTask<>(testCall1);
        FutureTask<String> futureTask2 = new FutureTask<>(testCall1);
        Thread thread1 = new Thread(futureTask1);
        Thread thread2 = new Thread(futureTask2);
        thread1.start();
        thread2.start();
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
    


class TestCall implements Callable<String>
    @Override
    public String call() throws Exception 
        System.out.println("start");
        return "hello";
    

以上是关于开启一个线程的方法?的主要内容,如果未能解决你的问题,请参考以下文章