Thread(多线程使用以及四种创建方式)

一、实现Runable接口,重新run方法
1、同步代码块
//	模拟卖票系统
class Window implements Runnable{
    private int ticket = 100;
    Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            synchronized (obj) {//Window.class  this   锁的是对象,所以三者都可以
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":票号为:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }

        }
    }
}

public class ThreadTest1 {
    public static void main(String[] args) {
        Window test1 = new Window();

        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test1);
        Thread thread3 = new Thread(test1);

        thread1.setName("窗口一");
        thread2.setName("窗口二");
        thread3.setName("窗口三");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
2、同步方法
    private int ticket = 100;
    @Override
    public void run() {
       while (true){
           show();
           if (ticket <= 0){
               break;
           }
       }
    }

    public synchronized void show(){
        //this
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":票号为:" + ticket);
            ticket--;
        }
    }
3、加锁还可以是lock锁
//lock和synchronized的区别,前者需要自己关闭,后者自动关闭
@Override
    public void run() {
        while (true){
            try {
                //调用lock
                lock.lock();

                if (ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" +ticket);
                    ticket--;
                }else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
二、继承Thread类重写run方法
    public static void main(String[] args) {
        ThreadTest1 thread1 = new ThreadTest1();
        Thread thread = new Thread(thread1);
        thread.start();

        Thread thread2 = new Thread(thread1);
        thread2.start();
    }

 class ThreadTest1 extends Thread{
     @Override
     public void run() {
         for (int i = 0; i < 100; i++) {
             if (i % 2 == 0){
                 System.out.println(Thread.currentThread().getName()+":"+i);
             }
         }
     }
}

三、实现Callable接口,重新run方法
public class CallableTest {
    //可以抛出异常,支持泛型
    public static void main(String[] args) {
    
        //2、创建实现了Callable接口的对象
        NumThread thread = new NumThread();
        
        //3、将实现了Callable接口的对象作为类的对象传递给FutureTask的构造器中
        FutureTask futureTask =  new FutureTask(thread);
        
        //4、FutureTask的对象作为类的对象传递给Thread构造器中
        new Thread(futureTask).start();
        
        try {
            Object sum = futureTask.get();
            //get的返回值就是FutureTask 构造参数Callable的call方法
            
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

//1、创建一个类实现Callable接口,实现call方法
class NumThread implements Callable{
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 50; i++) {
            if (i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
四、使用线程池创建线程
public class ThreadPollTest {
    
    private ExecutorService service;
    
    public static void main(String[] args) {
        
        ExecutorService service = Executors.newFixedThreadPool(10);
        //service.submit()适用于Runnable
        //service.execute()适用于Callable
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //管理线程池
        //service1.setCorePoolSize(15);
        System.out.println(service.getClass());

        service.execute(new NumberThread());
        //不用归还
        service.shutdown();
    }
}

class NumberThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + i);
            }
        }
    }
}
五、多线程常用方法
Thread.yield();
//让出CPU执行权,自己和其他线程一起再次抢占
start();
//线程开启
sleep(long millis) 
//开启睡眠状态,过了millis毫秒时开始执行,不释放锁
setPriority(int newPriority)
getPriority() 
//设置和得到线程的优先级,1-10,默认是5
setName(String name) 
getName() 
//设置线程的名字和得到名字
setDaemon(boolean on) 
//设置线程为守护线程
join() 
//加入新的一个线程,并且需要新的线程执行完,这个线程才可以执行
interrupt() 
//中断线程
interrupted() 
//判断线程中断
getState() 
//得到线程的状态
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值