java 多线程实现的几种方式:
1、extends Thread
2、implements Runnable
3、implements Callable<>
下面上代码:
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; /** * Created by root on 17-9-30. */ public class Test4Thread { public static void main(String[] args) throws Exception { //********************** MyThread1 myThread1_1=new MyThread1("myThread1_1"); MyThread1 myThread1_2=new MyThread1("myThread1_2"); MyThread1 myThread1_3=new MyThread1("myThread1_3"); myThread1_1.start(); myThread1_2.start(); myThread1_3.start(); //*********************** MyThread2 myThread2 = new MyThread2(); Thread t2_1 = new Thread(myThread2); Thread t2_2 = new Thread(myThread2); Thread t2_3 = new Thread(myThread2); t2_1.setName("MyThread2_1"); t2_2.setName("MyThread2_2"); t2_3.setName("MyThread2_3"); t2_1.start(); t2_2.start(); t2_3.start(); //************************** MyThread3 myThread3=new MyThread3(); FutureTask<String> futureTask1=new FutureTask<String>(myThread3); FutureTask<String> futureTask2=new FutureTask<String>(myThread3); FutureTask<String> futureTask3=new FutureTask<String>(myThread3); Thread t3_1 = new Thread(futureTask1); Thread t3_2 = new Thread(futureTask2); Thread t3_3 = new Thread(futureTask3); t3_1.setName("MyThread3_1"); t3_2.setName("MyThread3_2"); t3_3.setName("MyThread3_3"); t3_1.start(); t3_2.start(); t3_3.start(); System.out.println(futureTask1.get()); System.out.println(futureTask2.get()); System.out.println(futureTask3.get()); } } class MyThread1 extends Thread { int tickets = 5; public MyThread1(String name) { super(name); } @Override public void run() { for (; tickets > 0; ) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + tickets--); } } } class MyThread2 implements Runnable { int tickets = 5; public void run() { for (; tickets > 0; ) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + tickets--); } } } class MyThread3 implements Callable<String> { int tickets=5; public String call() throws Exception { for (; tickets > 0; ) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + tickets--); } return Thread.currentThread().getName() + ":" +"卖完了"; } }
运行结果:
myThread1_1:5 myThread1_2:5 myThread1_3:5 myThread1_1:4 myThread1_3:4 myThread1_2:4 myThread1_1:3 myThread1_2:3 myThread1_3:3 myThread1_1:2 myThread1_3:2 myThread1_2:2 myThread1_1:1 myThread1_3:1 myThread1_2:1
MyThread2_1:5 MyThread2_2:5 MyThread2_3:4 MyThread2_1:3 MyThread2_2:2 MyThread2_3:1 MyThread2_1:0 MyThread2_2:-1
MyThread3_1:5 MyThread3_2:4 MyThread3_3:3 MyThread3_1:2 MyThread3_2:1 MyThread3_1:卖完了 MyThread3_2:卖完了 MyThread3_3:0 MyThread3_3:卖完了
可以看到,后在需要实现多线程操作公工数据时最好用Runable 、Callable接口的方式,当然也可以用Thread (类似Runable的方式实现)。