创建多线程的四个方式

31 篇文章 0 订阅

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 “卖完了”;
}
}
//创建多线程方式四,线程池

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzh.start();

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值