多线程(二)

23 篇文章 0 订阅

让出CPU

package cn.cast;

@SuppressWarnings({ "rawtypes", "unchecked" }) // 去除黄色提示
public class HelloWorld {
    public static void main(String[] args) {
        new MyThread().start();
        new MyThread().start();
    }

}

class MyThread extends Thread {
    public void run() {
        for(int i = 1; i <= 1000; i++) {
            if(i % 20 == 0) {
                Thread.yield();
            }

            System.out.println(getName() + "...." + i);
        }
    }
}

优先级

package cn.itcast.thread;

public class Demo2_Priority {

    /**
     * @param args
     * setPriority()设置线程优先级
     * 最高级别是10Thread.MAX_PRIORITY
     * 最低级别是1Thread.MIN_PRIORITY
     */
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                for(int i = 0; i < 1000; i++) {
                    System.out.println(getName() + "...aaaaaaaaaaaaa");
                }
            }
        };

        Thread t2 = new Thread() {
            public void run() {
                for(int i = 0; i < 1000; i++) {
                    System.out.println(getName() + "...bb");
                }
            }
        };

        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);

        t1.start();
        t2.start();
    }

}

设置关机

package cn.itcast.thread;

import java.io.IOException;

public class Demo4_Runtime {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        Runtime r = Runtime.getRuntime();               //获取到Runtime这个类实例对象
        //r.exec("shutdown -s -t 300");                 //设置关机
        r.exec("shutdown -a");
    }

}

定时器

package cn.cast;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

@SuppressWarnings({ "rawtypes", "unchecked" }) // 去除黄色提示
public class HelloWorld {
    /**
     * @param args
     * Timer是一个计时器类,在指定时间执行指定任务
     * @throws InterruptedException 
     */
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException {
        Timer t = new Timer();                          //创建计时器对象
        //设置指定时间点执行任务,年份减去1900,月份减1
        t.schedule(new MyTimerTask(), new Date(118, 6, 8, 16, 30 , 30)); 

        //只执行一次 singleshot
        t.schedule(new MyTimerTask(),3000);
        //某个时间点之后开启定时器,如果是马上开启只需要newData即可
        t.schedule(new MyTimerTask(), new Date(118, 6, 8, 16, 33 , 00),3000);
        while(true) {
            Thread.sleep(1000);
            System.out.println(new Date());
        }
    }

}


class MyTimerTask extends TimerTask {

    @Override
    public void run() {
        System.out.println("起床背英语单词");
    }

}

条件锁

package cn.itcast.thread;

public class Demo06_Notify {

    /**
     * @param args
     */
    public static void main(String[] args) {
        final Printer p = new Printer();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print1();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print2();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print3();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}
//等待唤醒机制
/*
 * 在同步代码块中锁对象是谁,就用哪个对象来调用wait
 * 为什么wait方法和notify方法需要定义在Object
 * 所有的对象都是Object的子类对象,而所有的对象都可以当作锁对象
 * 
 * sleep方法和wait方法的区别
 * 1,sleep方法必须传入参数,参数就是时间,当时间到了,不用唤醒自动醒来
 *  wait方法不是必须传入参数,如果没有参数,遇到wait就等待,如果传入参数,等参数的时间到后等待
 * 2,sleep方法在同步中不释放锁
 *   wait方法在同步中释放锁
 */
class Printer {
    private int flag = 1;                               //定义标记
    private Object obj = new Object();
    public void print1() throws InterruptedException {
        synchronized(this) {
            while(flag != 1) {                              //如果标记不为1就等待
                this.wait();
            }
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.print("5");
            System.out.print("\r\n");
            flag = 2;
            this.notifyAll();                               //随机唤醒另一条线程
        }
    }

    public void print2() throws InterruptedException {
        synchronized(this) {
            while(flag != 2) {                              //如果标记不为2就等待
                this.wait();                            //线程2等待
            }
            System.out.print("a");
            System.out.print("b");
            System.out.print("c");
            System.out.print("d");
            System.out.print("\r\n");
            flag = 3;
            this.notifyAll();                               //随机唤醒另一条线程
        }
    }

    public void print3() throws InterruptedException {
        synchronized(this) {
            while(flag != 3) {                              //如果标记不为2就等待
                this.wait();                            //线程3等待
            }
            System.out.print("i");
            System.out.print("t");
            System.out.print("c");
            System.out.print("a");
            System.out.print("s");
            System.out.print("t");
            System.out.print("\r\n");
            flag = 1;
            //this.notify();                                //随机唤醒另一条线程
            this.notifyAll();                               //唤醒所有等待的线程             
        }
    }
}

互斥锁

package cn.itcast.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Demo07_ReentrantLock {

    /**
     * 1.5版本的新特性互斥锁
     * 1.同步
     * 使用ReentrantLock类的lock()和unlock()方法进行同步
     * 2.通信
     * 使用ReentrantLock类的newCondition()方法可以获取Condition对象
     * 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
     * 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
     */
    public static void main(String[] args) {
        final Printer2 p = new Printer2();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print1();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print2();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while(true) {
                    try {
                        p.print3();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}

class Printer2 {
    private ReentrantLock r = new ReentrantLock();      //创建互斥锁对象
    private Condition c1 = r.newCondition();            //创建监视器
    private Condition c2 = r.newCondition();
    private Condition c3 = r.newCondition();
    private int flag = 1;                               //定义标记
    //private Object obj = new Object();
    public void print1() throws InterruptedException {
        r.lock();
            if(flag != 1) {                             //如果标记不为1就等待
                c1.await();
            }
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.print("5");
            System.out.print("\r\n");
            flag = 2;
            c2.signal();
        r.unlock();
    }

    public void print2() throws InterruptedException {
        r.lock();
            if(flag != 2) {                             //如果标记不为2就等待
                c2.await();                         //线程2等待
            }
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.print("\r\n");
            flag = 3;
            c3.signal();                        //随机唤醒另一条线程
        r.unlock();
    }

    public void print3() throws InterruptedException {
        r.lock();
            if(flag != 3) {                             //如果标记不为2就等待
                c3.await();                     //线程3等待
            }
            System.out.print("i");
            System.out.print("t");
            System.out.print("c");
            System.out.print("a");
            System.out.print("s");
            System.out.print("t");
            System.out.print("\r\n");
            flag = 1;
            //this.notify();                                //随机唤醒另一条线程
            c1.signal();                            //唤醒所有等待的线程             
        r.unlock();
    }
}

线程组

package cn.itcast.thread;

public class Demo08_ThreadGroup {

    /**
     * @param args
     * public final ThreadGroup getThreadGroup()//通过线程对象获取他所属于的组
     * public final String getName()//通过线程组对象获取他组的名字
     * 
     * 默认是主线程组
     */
    public static void main(String[] args) {
        //demo1();
        ThreadGroup tg = new ThreadGroup("我是一个线程组");
        Thread t1 = new Thread(tg, new MyRunnable(), "张三");     //将指定线程加入指定的线程组
        Thread t2 = new Thread(tg, new MyRunnable(), "李四");     //将指定线程加入指定的线程组

        //tg.setDaemon(true);
        System.out.println(tg.getName());
    }

    public static void demo1() {
        MyRunnable mr = new MyRunnable();
        Thread t1 = new Thread(mr, "张三");
        Thread t2 = new Thread(mr, "李四");
        ThreadGroup tg1 = t1.getThreadGroup();
        ThreadGroup tg2 = t2.getThreadGroup();

        System.out.println(tg1.getName());
        System.out.println(tg2.getName());
    }

}

线程池

package cn.itcast.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo09_Executors {

    /**
     * JDK5新增了一个Executors工厂类来产生线程池,有如下几个方法
        * public static ExecutorService newFixedThreadPool(int nThreads)
        * public static ExecutorService newSingleThreadExecutor()
        * 这些方法的返回值是ExecutorService对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程。它提供了如下方法
        * Future<?> submit(Runnable task)
        * <T> Future<T> submit(Callable<T> task)
    * 使用步骤:
        * 创建线程池对象
        * 创建Runnable实例
        * 提交Runnable实例
        * 关闭线程池
     */
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);     //创建线程池,可以放两条线程
        MyRunnable mr1 = new MyRunnable();                          //创建Runnable的子类对象
        MyRunnable mr2 = new MyRunnable();

        pool.submit(mr1);                                           //放在线程池并提交
        pool.submit(mr2);

        pool.shutdown();                                            //关掉线程池,不接受新任务
    }

}

Callable的使用

package cn.itcast.thread;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {

    private int num;
    public MyCallable(int num) {
        this.num = num;
    }
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for(int i = 1; i <= num; i++) {
            sum = sum + i;
        }
        return sum;
    }

}
package cn.itcast.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Demo10_Callable {

    /**
     * @param args
     * @throws ExecutionException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newFixedThreadPool(2);     //创建线程池,可以放两条线程
        MyCallable mc1 = new MyCallable(100);
        MyCallable mc2 = new MyCallable(200);

        Future<Integer> f1 = pool.submit(mc1);                                          //放在线程池并提交
        Future<Integer> f2 = pool.submit(mc2);

        Integer i1 = f1.get();                                      //获取结果
        Integer i2 = f2.get();

        System.out.println(i1);
        System.out.println(i2);
        pool.shutdown();                                            //关掉线程池,不接受新任务
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值