Java thread creation method (inherit Thread, implement Runnable, FutureTask class)

Inherit Thread

	public static class MyThread extends Thread
    {
    
    
        @Override
        public void run()
        {
    
    
            System.out.println("i am a thread");
        }
    }
	
	public static void main(String[] args)
    {
    
    
       	MyThread myThread = new MyThread();
       	myThread.start();
    }

Implement Runnable

	public static class RunnableTask implements Runnable
    {
    
    
        @Override
        public void run()
        {
    
    
            System.out.println("i am a child thread");
        }
    }
    public static void main(String[] args)
    {
    
    
    	RunnableTask runnableTask = new RunnableTask();
        new Thread(runnableTask).start();
        new Thread(runnableTask).start();
    }

FutureTask

	public static class CallerTask implements Callable<String>
    {
    
    

        @Override
        public String call() throws Exception
        {
    
    
            return "hellow";
        }
    }
	
	public static void main(String[] args)
    {
    
    
        FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
        new Thread(futureTask).start();

        String result = null;
        try
        {
    
    
            result = futureTask.get();
        }
        catch (ExecutionException e)
        {
    
    
            e.printStackTrace();
        }
        catch (InterruptedException e)
        {
    
    
            e.printStackTrace();
        }
        System.out.println(result);
    }
输出:hellow

After calling the strat method, the program is not executed immediately but in a ready state, waiting to obtain CPU resources

Guess you like

Origin blog.csdn.net/weixin_43663421/article/details/109360593