Java——多线程总结

/*class MyThread extends Thread{
    public void run(){
        try{
            Thread.currentThread().sleep(3000);
        }catch(InterruptedException e){
        }
        System.out.println("MyThread running");
    }
}
public class ThreadTest{
    public static void main(String[] args){
        MyThread t = new MyThread();
        t.run();
        t.start();
        System.out.println("Thread Test");
    }
}
*/
/*
MyThread t = new MyThread();创建了一个子线程,t.run();调用run()方法就是一个普通的方法调用
执行Thread.currentThread().sleep(3000);因为当前线程是主线程,所以主线程睡3秒,睡够3秒打印
"MyThread running",然后主线程启动子线程,一种可能是主线程仍然持有CPU,主线程打印"Thread Test",
主线程结束,然后子线程得到CPU,子线程先睡3秒,然后打印"MyThread running",另一种可能是子线程
立刻得到CPU,子线程先睡3秒,在子线程睡得时候主线程得到CPU,主线程打印"Thread Test",然后子线程
睡够三秒,打印"MyThread running"
*/

class test{
    public static void main(String[] args){
        //使用匿名内部类创建线程

        //创建了一个Thread类的子类对象
        new Thread(){
            public void run(){

            }
        }.start();

        //创建线程的第二种方式
        new Thread(new Runnable()){
            public void run(){

            }
        }

        Runnable r = new Runnable(){
            public void run(){

            }
        };
        new Thread(r).start();
    }
}

/*
1、生产者消费者:

使用while()替代if,让线程被唤醒后先去判断标记
使用notifyAll()来唤醒所有线程,防止出现死锁

2、jdk1.5多线程的实现方式
Lock:
    Lock lock = new ReentrantLock();

    lock.lock();
        需要写在同步代码块中的代码
    lock.unlock();

    //唤醒对方的线程则创建两个Condition对象
    Condition pro = lock.newCondition();
    Condition con = lock.newCondition();
    con.await();
    con.signal();
    con.signalAll();

3、多生产多消费

4、线程的停止

5、守护线程 setDaemon(boolean)

6、join()可以让线程优先持有CPU
*/
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值