创建多线程的四个方式

mac2024-03-23  26

package xianTest; import java.util.concurrent.*; public class testOne { public static void main(String[] args) throws ExecutionException, InterruptedException { //方式一 // one o1 = new one(); // one o2 = new one(); // one o3 = new one(); // o1.setName(“窗口一”); // o2.setName(“窗口二”); // o3.setName(“窗口三”); // o1.start(); // o2.start(); // o3.start(); //方式二 // two tw = new two(); // Thread t1 = new Thread(tw); // Thread t2 = new Thread(tw); // Thread t3 = new Thread(tw); // t1.setName(“窗口一”); // t2.setName(“窗口二”); // t3.setName(“窗口三”); // t1.start(); // t2.start(); // t3.start(); //方式三 // three th1 = new three(); three th2 = new three(); three th3 = new three(); FutureTask futureTask1 = new FutureTask(th1); FutureTask futureTask2 = new FutureTask(th2); FutureTask futureTask3 = new FutureTask(th3); Thread t1= new Thread(futureTask1); Thread t2= new Thread(futureTask2); Thread t3= new Thread(futureTask3); t1.setName(“窗口1”); t2.setName(“窗口2”); t3.setName(“窗口3”); t1.start(); t2.start(); t3.start(); System.out.println(futureTask1.get()); //方式四 // ExecutorService Service = Executors.newFixedThreadPool(10); // ThreadPoolExecutor service = (ThreadPoolExecutor)Service; // service.setMaximumPoolSize(10); //最大线程数 // service.setCorePoolSize(5); //核心池的大小 // service.execute(new two()); // service.execute(new two()); // service.execute(new two()); // service.shutdown(); // service.setKeepAliveTime()

}

}

//创建多线程方式一,继承Thread()方法,同步监视器 class one extends Thread{ public static int piao=100; @Override public void run() { while (true){ synchronized (getClass()){ if(piao>=1){ System.out.println(Thread.currentThread().getName()+“窗口卖票”+piao+“号”); piao–; }else { break; }

} } }

} //创建多线程方式二,实现Runable接口,同步方法 class two implements Runnable { public static int piao = 100;

public void run() { while (true) { show(); if(piao<=0){ break; } } } public synchronized void show(){ if(piao>=1){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"卖票,票号"+piao); piao--; } }

} //创建多线程方式三,实现Callable接口 class three implements Callable { public static int piao=100; @Override public Object call() { while(true){ synchronized (getClass()){ if(piao>=1){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+“卖票,号为”+piao); piao–; }else { break; } } } return “卖完了”; } } //创建多线程方式四,线程池

最新回复(0)