java 多线程入门

实现多线程的两种基本方法

  1. 继承Thread类
  2. 实现Runnable接口(优先选择)
public class TestThread1 {
    public static void main(String[] args) {
        Runner1 runner = new Runner1();
        //线程启动
        runner.start();

        //runner.run();     //方法调用
        //线程启动
        Thread thread = new Thread(runner);
        thread.start();

        for(int i = 0; i < 100; i++) {
            System.out.println("main:"+i);
        }
    }
}

//class Runner1 implements Runnable {
class Runner1 extends Thread {
    public void run() {
        for(int i = 0; i < 100; i++) {
            System.out.println("runner1:"+i);
        }
    }
}

一个线程对象启动两个线程

public class TestThread2 {
    public static void main(String[] args) {
        Runner2 r2 = new Runner2();
        //一个线程对象启动两个线程
        Thread t1 = new Thread(r2);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }
}

//class Runner1 implements Runnable {
class Runner2 extends Thread {
    public void run() {
        for(int i = 0; i < 100; i++) {
            System.out.println("runner2:"+i);
        }
    }
}

正常终止子线程

public class TestThread3 {
    public static void main(String[] args) {
        Runner3 r3 = new Runner3();
        Thread t = new Thread(r3);
        t.start();
        for(int i = 0; i < 100; i++) {
            if(i % 10 ==0 & i > 0) {
                System.out.println("main:" + i);
            }
        }
        System.out.println("main over");
        r3.shutDown();  //正常终止子线程
    }
}
class Runner3 implements Runnable {
    private boolean flag = true;
    public void run() {
        int i = 0;
        while(flag) {
            System.out.println(" " + i++);
        }
    }

    public void shutDown() {
        flag = false;
    }
}

isAlive()方法测试线程是否存活

public class TestThread4 {
    public static void main(String[] args) {
        Thread t = new Runner5();
        t.start();

        for(int i = 0; i < 50; i++) {
            System.out.println("mainTread:" + i);
        }
    }
}

class Runner5 extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().isAlive()); //线程是否存活
        for(int i = 0; i < 50; i++) {
            System.out.println("subThread:" + i);
        }
    }
}

yield(),join(),interrupt()方法

1 yield()方法:给其他线程可以执行的机会

public class TestYield {
    public static void main(String[] args) {
        MyThread3 t1 = new MyThread3("线程1");
        MyThread3 t2 = new MyThread3("线程2");
        t1.start();
        t2.start();
    }
}

class MyThread3 extends Thread {
    public MyThread3 (String s) {
        super(s);
    }
    public void run() {
        for(int i = 1; i <= 100; i++) {
            System.out.println(getName() + ":"+i);
            if(i % 10 == 0) {
                yield();    //让出CPU,给其他线程执行的机会
            }
        }
    }
}

2 join()方法:将多个线程合并,相当于方法调用

public class TestJoin {
    public static void main(String[] args) {
        MyThread2 myThread2 = new MyThread2("abcde");
        myThread2.start();
        try {
            myThread2.join();  //相当于方法调用
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 0; i < 10; i++) {
            System.out.println("main:"+i);
        }
    }
}

class MyThread2  extends Thread {
    public MyThread2(String s) {
        super(s);
    }

    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println("MyThread2:"+i);
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}

3 interrupt()方法:终止子线程, 该方法比较暴力,建议少用

public class TestInterrupt {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e){}
        myThread.interrupt(); //中断,抛异常,子线程结束
    }
}
class MyThread extends Thread {
    boolean flag = true;
    public void run() {
        while(flag) {
            System.out.println("===" + new Date() + "===");
            try {
                sleep(1000);  //睡眠1秒
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}

线程优先级

public class TestPriority {
    public static void main(String[] args) {
        Thread t1 = new Thread(new T1());
        Thread t2 = new Thread(new T2());
        //Thread.MAX_PRIORITY == 10;
        //Thread.MIN_PRIORITY == 1;
        //Thread.NORM_PRIORITY == 5;
        //优先级越高,执行时间越长
        t1.setPriority(Thread.NORM_PRIORITY + 5); //设置优先级为8
        t1.start();
        t2.start();
    }
}

class T1 implements Runnable {
    public void run() {
        for(int i = 0; i < 1000; i++) {
            System.out.println("T1:"+i);
        }
    }
}

class T2 implements Runnable {
    public void run() {
        for(int i = 0; i < 1000; i++) {
            System.out.println("======T2:"+i);
        }
    }
}

死锁

//死锁
public class TestDeadLock implements Runnable{
    public int flag = 1;
    static Object o1 = new Object(), o2 = new Object();

    public void run() {
        System.out.println("flag = " + flag);
        if(flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }

        if(flag == 2) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("2");
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();

        td1.flag = 1;
        td2.flag = 2;

        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);

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

生产者消费者问题

//生产者消费者问题
public class ProducerConsumer {
    public static void main(String[] args) {
        SyncStack ss = new SyncStack();
        Producer p = new Producer(ss);
        Consumer c = new Consumer(ss);
        new Thread(p).start();
        new Thread(c).start();
    }
}

//馒头
class WoTou {
    int id;  //标识馒头
    WoTou(int id) {
        this.id = id;
    }

    public String toString() {
        return "WoTou: " + id;
    }
}

//容器
class SyncStack {
    int index = 0;
    WoTou[] arrWT = new WoTou[6];

    //放入馒头
    public synchronized void push(WoTou wt) {
        while(index == arrWT.length) {
            try {
                this.wait();   //当前线程停止,释放锁.要加锁才能调用wait()
            } catch (InterruptedException e) {
                e.printStackTrace();
            }  
        }
        this.notify();  //唤醒一个当前对象的被锁住的线程
        arrWT[index] = wt;
        index++;
    }

    //拿出馒头
    public synchronized WoTou pop() {
        while(index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        return arrWT[index];
    }
}

//生产者有一个容器的引用,这样才知道生产出来的馒头放在何处
class Producer implements Runnable {
    SyncStack ss = null;
    Producer(SyncStack ss) {
        this.ss = ss;
    }

    public void run() {
        for(int i = 0; i < 20; i++) {
            WoTou wt = new WoTou(i); //生产馒头
            System.out.println("生产了:" + wt);
            ss.push(wt);
            try {
                Thread.sleep((long)(Math.random() * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者有一个容器的引用,这样才知道从哪里拿馒头
class Consumer implements Runnable {
    SyncStack ss = null;
    Consumer(SyncStack ss) {
        this.ss = ss;
    }

    public void run() {
        for(int i = 0; i < 20; i++) {
            WoTou wt = ss.pop();  //拿出馒头
            System.out.println("消费了:" + wt);
            //System.out.println(wt.toString());
            try {
                Thread.sleep((long)(Math.random() * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

面试题

//面试题
public class TT implements Runnable{
    int b = 100;
    public synchronized void m1() throws Exception {
        b = 1000;
        Thread.sleep(5000);
        System.out.println("b = " + b);
    }

    public void m2() {  //在m1()执行时m2()也可以执行
        System.out.println(b);
    }

    public void run() {
        try {
            m1();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值