创建java程序线程的三种方式

xiaoxiao2021-02-28  53

三种启动线程的方式(注:一个进程可以有多个线程)

(1) 继承Thread类

Step1:创建一个继承于Thread类的子类;

Step2:重写Thread类的run()方法,方法内实现此子线程要实现的功能;

Step3:创建一个子类的对象;

Step4:调用线程的start()方法;启动此线程,然后调用相应的run()方法

注:一个线程只能调用一次start()方法

package Thread01; public class MyThread extends Thread { private int i; @Override public void run() { for (; i < 10; i++) { System.out.println(getName()+"\t"+i); } } } package Thread01; public class MyTest { public static void main(String[] args) { for (int i = 0; i <10; i++) { System.out.println(Thread.currentThread().getName()+"\t"+i+"======"); if(i==5){ MyThread mt2 =new MyThread(); MyThread mt =new MyThread(); mt2.start(); mt.start(); } } } public static long getMemory() { return Runtime.getRuntime().freeMemory(); } }

(2) 实现Runnable接口

Step1:创建一个实现Runnable接口的类;

Step2:实现接口的抽象方法;

Step3:创建一个实现Runnable接口的实现类对象;

Step4:将此对象作为形参传递给Thread类的构造器,创建Thread类的对象,此对象即为一个线程;

Step5:调用start()方法:启动线程并执行run()方法。

package Thread02; public class SecondThread implements Runnable{ private int i; public void run() { for (; i < 20; i++) { System.out.println(Thread.currentThread().getName()+" "+i); if(i==20) { System.out.println(Thread.currentThread().getName()+"执行完毕"); } } } } package Thread02; public class MyTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+" "+i); if(i==5) { SecondThread s1=new SecondThread(); Thread t1=new Thread(s1,"线程1"); Thread t2=new Thread(s1,"线程2"); t1.start(); t2.start(); } } } } (3)实现callable接口

package Thread03; import java.util.concurrent.Callable; public class Target implements Callable<Integer> { int i=0; public Integer call() throws Exception { for (; i < 20; i++) { System.out.println(Thread.currentThread().getName()+""+i); } return i; } } package Thread03; import java.util.concurrent.FutureTask; public class ThirdThread { public static void main(String[] args) { Target t1=new Target(); FutureTask<Integer> ft=new FutureTask<Integer>(t1); Thread t2=new Thread(ft,"新线程"); t2.start(); try { System.out.println(ft.get()); } catch (Exception e) { // TODO: handle exception } } }
转载请注明原文地址: https://www.6miu.com/read-79150.html

最新回复(0)