java多线程3种基本实现方式

java多线程–起航

3种实现方式
package 多线程;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 多线程------基本实现方式
 */

//资源共享
class MyThread1 implements Runnable{
    private int ticket=10;
    @Override
    public void run() {
        for(int x=0;x<10;x++)
        if(this.ticket>=0){
            System.out.println("当前线程="+Thread.currentThread().getName()+",车票剩余="+this.ticket--);
        }
    }
}
//资源独享
class MyThread2 extends Thread{
    private int ticket=10;
    @Override
    public void run() {
        for(int x=0;x<10;x++)
            if(this.ticket>=0){
                System.out.println("当前线程="+Thread.currentThread().getName()+",车票剩余="+this.ticket--);
            }
    }
}

//返回值
class MyThread3 implements Callable<String>{
    private int ticket=10;
    @Override
    public String call() {
        for(int x=0;x<10;x++) {
            try {
                TimeUnit.SECONDS.sleep(1);
                if (this.ticket >= 0) {
                    System.out.println("当前线程=" + Thread.currentThread().getName() + ",车票剩余=" + this.ticket--);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
            return "票已售完";
    }
}

//测试类
public class ThreadDemo {
    public static void main(String  args[])throws Exception{
        //代理设计模式

        //数据共享
//        MyThread1 mt=new MyThread1();
//        new Thread(mt,"线程1").start();
//        new Thread(mt,"线程2").start();
//        new Thread(mt,"线程3").start();

         //独享数据
//        new MyThread2().start();
//        new MyThread2().start();
//        new MyThread2().start();

        //共享数据--冗余
//        MyThread2 mt2=new MyThread2();
//        new Thread(mt2,"线程1").start();
//        new Thread(mt2,"线程2").start();
//        new Thread(mt2,"线程3").start();

 
//start()方法执行 run()
//FutureTask类本质上实现了run()方法
/**源码
 *  private static final int NEW          = 0;
 *
 * public void run() {
 *         if (state != NEW ||
 *             !UNSAFE.compareAndSwapObject(this, runnerOffset,
 *                                          null, Thread.currentThread()))
 *             return;
 *         try {
 *             Callable<V> c = callable;
 *             if (c != null && state == NEW) {
 *                 V result;
 *                 boolean ran;
 *                 try {
 *                     result = c.call();
 *                     ran = true;
 *                 } catch (Throwable ex) {
 *                     result = null;
 *                     ran = false;
 *                     setException(ex);
 *                 }
 *                 if (ran)
 *                     set(result);
 *             }
 *         } finally {
 *             // runner must be non-null until state is settled to
 *             // prevent concurrent calls to run()
 *             runner = null;
 *             // state must be re-read after nulling runner to prevent
 *             // leaked interrupts
 *             int s = state;
 *             if (s >= INTERRUPTING)
 *                 handlePossibleCancellationInterrupt(s);
 *         }
 *     }
 *
 *       Possible state transitions:
 *      * NEW -> COMPLETING -> NORMAL
 *      * NEW -> COMPLETING -> EXCEPTIONAL
 *      * NEW -> CANCELLED
 *      * NEW -> INTERRUPTING -> INTERRUPTED
 *
 *      private volatile int state;
 *      private static final int NEW = 0;
 *      private static final int COMPLETING = 1;
 *      private static final int NORMAL = 2;
 *      private static final int EXCEPTIONAL = 3;
 *      private static final int CANCELLED = 4;
 *      private static final int INTERRUPTING = 5;
 *      private static final int INTERRUPTED = 6;
 *
 *    执行完一个线程state==2 则执行run()直接返回return;
  */
        MyThread3 mt3=new MyThread3();
        RunnableFuture<String> futureTask=new FutureTask<String>(mt3);
        new Thread(futureTask,"B").start();
        new Thread(futureTask,"A").start();
        System.out.println(futureTask.get());
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值