多线程

最近帮朋友写一个小程序,由于要处理的数据量巨大,所以考虑用多线程。因为很少写多线程的程序,所以开工前找了些资料,翻了翻书,自己也写了些练习代码。

由于自己记性不好,事后忘,所以将自己的一些心得写下来。

 

一、基本概念
线程可看成小的进程,即一个进程中可以有多个线程。
每个线程都是通过某个特定Threan对象所对应的run()方法来完成其操作的,方法run()称为线程体。
每一个线程通过调用Thead类的start()方法来启动一个线程,而不是run()方法。


二、继承与实现
要实现一个线程必需继承java.lang.Thread 类或实现java.lang.Runnable 接口。
由于java不像C++,无法多继承,所以建议实现Runnable接口。

例子:
public class MyThread extends Thead {
    @Override
    public void run() {
        ...
    }
}

public class MyRunnable implements Runnable {
    public void run() {
        ...   
    }
}

public class MyTest {
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        myThread.start();
   
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}


三、常用方法
start():让线程进入就绪状态;

run():必须重写的方法,在线程里运行的程序;

isAlive():判断线程是否还在,即线程是否还未终止;

getPriority():获得线程的优先级数值;
setPriority():设置线程的优先级数值,优先级越高,得到CPU的执行片越多。
    线程的优先级用数字表示,从1到10。
    一个线程的缺省优先级是5
    Thread.MIN_PRIORITY = 1
    Thread.MAX_PRIORITY = 10
    Thread.NORM_PRIORITY = 5

join():调用某线程的该方法,将当前线程与该线程"合并",即等待线程结束,再恢复当前线程的运行;

yield():让出CPU,当前线程进入就绪队列等待调度;

Thread.sleep(long millis):静态方法,让当前线程睡眠所定的毫秒数;

wait():将当前线程进入对象的wait pool;
notify():唤醒wait pool中的一个等待线程;
notifyAll():唤醒wait pool中的所有等待线程;

currentThread():拿到当前线程对象;
currentThread().isAlive():当前线程对象是否还在;

interrupt():强制中断线程;
stop() :与interrupt()一样,但已不建议使用;

setDaemon():设置守护线程;
isDaemon():该线程是否为守护线程;

synchronized/synchronized():线程锁



四、典型例子
1、死锁
public class Deadlock implements Runnable {

    private final Object obj1 = "Object1";
    private final Object obj2 = "Object2";

    private int type = 1;

    public Deadlock(int type) {
        this.type = type;
    }

    /**
     * 死锁方法
    *   
     */
    public void deadlockMethod(){
        if (type == 1) {
            System.out.println("type1");
            synchronized (obj1) {
                System.out.println(type + " 使用" + obj1);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(obj2) {
                    System.out.println(type + " 使用" + obj2);
                }
            }
        } else if (type == 2) {
            System.out.println("type2");
            synchronized (obj2) {
                System.out.println(type + " 使用" + obj2);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(obj1) {
                    System.out.println(type + " 使用" + obj1);
                }
            }

        }
    }
   
    public void run() {
        deadlockMethod();
    }

    public static void main(String[] args) {
        Deadlock dl1 = new Deadlock(1);
        Deadlock dl2 = new Deadlock(2);
        Thread thread1 = new Thread(dl1);
        Thread thread2 = new Thread(dl2);
        thread1.start();
        thread2.start();
    }
}


执行结果:
type1
type2
使用Object1
使用Object2
程序就停在这里不动了,必需手动关闭

总结: 解决线程死锁的最好方法是放大锁定粒度,就是不要分别锁两个小的线程,而是锁定拥有两个线程的方法或对象,当然,这样会使效率降低,但能保证程序的正常运行。

修改method()方法

public synchronized void deadlockMethod() {
        if (type == 1) {
            System.out.println("type1");

            System.out.println(type + " 使用" + obj1);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(type + " 使用" + obj2);

        } else if (type == 2) {
            System.out.println("type2");

            System.out.println(type + " 使用" + obj2);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(type + " 使用" + obj1);
        }
    }

运行结果:
type1
type2
1 使用Object1
2 使用Object2
1 使用Object2
2 使用Object1
程序运行结束


2、线程同步——消费者与生产者
/**
 * 生产者类
 *   
 */
public class Producer extends Thread {
   
    private SyncStack stack;
    private int number;

    public Producer(SyncStack stack, int number) {
        this.stack = stack;
        this.number = number;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            stack.put(i);
            System.out.println("Producer" + number + " put: " + i);
            try {
                sleep((int) (Math.random() * 100));
            } catch (InterruptedException e) {
            }
        }
    }
}

/**
 * 消费者类
 *
 */
public class Consumer extends Thread {
    private SyncStack stack;
    private int number;

    public Consumer(SyncStack stack, int number) {
        this.stack = stack;
        this.number = number;
    }

    @Override
    public void run() {
        int value = 0;
        for (int i = 0; i < 10; i++) {
            value = stack.get();
            System.out.println("Consumer" + number + " get: " + value);
        }
    }
}

/**
 * 同步类
 *
 */
public class SyncStack {
    private int contents;
    private boolean available = false;

    public synchronized void put(int value) {
        while (available == true) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        contents = value;
        available = true;
        notifyAll();
    }


    public synchronized int get() {
        while(available == false) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        available = false;
        notifyAll();
        return contents;
    }

    public static void main(String[] args) {
        SyncStack stack = new SyncStack();
        Producer producer1 = new Producer(stack, 1);
        Consumer consumer1 = new Consumer(stack, 1);

        producer1.start();
        consumer1.start();

    }
}


五、斯文的终止
从线程的常用方法中可以找到interrupt()stop() 两个方法,两个方法都是终止线程的,由于stop()太暴力太不安全,所以Sun已经公示该方法已经过时。而interrupt()方法虽然没过时,但仍然太粗鲁,而且还有可能抛出SecurityException,所以建议用while。

例子:
public class ExampleThread implements Runnable{
    private boolean action = true;

    public void shutdown(){
        action = false;
    }

    public void run(){
       
while(action){
            //N条执行代码
        }
    }

}

其他程序只要调用 ExampleThread 的 shutdown()方法,就能终止线程,这样一是能保证run()方法中所有的代码能顺利完成,二是不用担心抛出异常。


六、我等你
同步辅助类 java.util.concurrent.CountDownLatch ,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待

用给定的计数 new CountDownLatch
CountDownLatch latch = new CountDownLatch(threadCount);

递减线程数量countDown()
latch.countDown();

等待其他线程的完结await()
latch.countDown();

列子
public class MyThread extends Thread {
    private CountDownLatch latch;
    private String name;
   
    public MyThread(CountDownLatch latch , String name){
        this.latch = latch;
        this.name = name;
        }
      
        public void run() {
        System.out.println(name + " 运行");
        for (int i = 0; i < 1000; i++) {
            try {
                sleep(500);
            } catch (InterruptedException e) {}
        }

        latch.countDown();

        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
      
        for(int i=0; i < 5; i++) {
        TestCountDownLatch tcdl = new TestCountDownLatch(latch ,("tcdl" + i));
        }
   
        latch.await(); //等待所有子线程结束
        System.out.println("main方法结束");
    }
}

运行结果:
tcdl0 运行
tcdl1 运行
tcdl2 运行
tcdl3 运行
tcdl4 运行
main方法结束


六、守护线程
Java有两种Thread:守护线程、用户线程;之前看到的例子都是用户线程。
Daemon,守护线程是一种“在后台提供通用性支持”的线程,它并不属于程序本体。守护线程主要用于用户线程的调配管理。
我们用的最多的守护线程是Java垃圾回收器。

setDaemon():设置守护线程;
    true  为守护模式;
    false 为用户模式;
isDaemon():该线程是否为守护线程;

例子:
public class MainMethod {
    public void work(){
        Vector<String> works = new Vector<String>(7);
        works.add("洗衣服");
        works.add("洗碗");       
        works.add("扫地");
        works.add("抹窗");
        works.add("洗厕所");
        works.add("通下水道");
        works.add("补屋顶");

        DaemonThread daemon = new DaemonThread(works, "管家");
        daemon.findWorker(2);
        daemon.setDaemon(true);
        daemon.start();
        for (int i = 0; i < 2; i++) {
            UserThread worker = new UserThread("工人" + i);
            daemon.enrol(worker);
            worker.start();
        }
    }
   
    public static void main(String[] args){
        MainMethod mainMethod = new MainMethod();
        mainMethod.work();
    }
}


/**
 * 守护线程
 *
 */
public class DaemonThread extends Thread {
   
    private List<UserThread> workers;
    private Vector<String> works;
    private String name;
   
    public DaemonThread(Vector<String> works, String name){
        this.works = works;
        this.name = name;
    }
   
    public void findWorker(int count){
        System.out.println("找来" + count + "个工人");
        workers = new ArrayList<UserThread>(count);
    }
   
    public void enrol(UserThread worker){
        workers.add(worker);
    }

    private void assignWork(){
        for (int i = 0; i < workers.size(); i++) {
            if(workers.get(i).isWait()){
                assignWork(i);
            }
        }
    }
   
    private void assignWork(int num){
        if(works.size() > 0){
            System.out.println(name + ": " + workers.get(num).getWorkerName() + ",你现在去" + works.get(0));
            workers.get(num).acquireNewWork(works.get(0));
            works.remove(0);
            workers.get(num).startWorking();
        } else {
            workers.get(num).shutdown();
        }
    }
   
    @Override
    public void run() {
        while(true){
            assignWork();
        }
    }
   
}

/**
 * 用户线程
 *
 */
public class UserThread extends Thread {
   
    private boolean working = true;
    private boolean action = false;
   
    private String name;
    private String work;
   
    public UserThread(String name){
        this.name = name;
    }

    public String getWorkerName() {
        return name;
    }
   
    public void acquireNewWork(String newWork){
        this.work = newWork;
    }
   
    public void shutdown(){
        working = false;
    }
   
    public void startWorking(){
        action = true;
    }
   
    public boolean isWait(){
        return action?false:true;
    }
   
    private void working(){
        while(action){
            for (int i = 0; i < 3; i++) {
                System.out.println(name + ": 努力" + work);
                if((i%4)== 1){
                    System.out.println(name + ": 休息一下");
                    Thread.yield();
                }
            }
            System.out.println(name + ": " + work + "——工作完毕");
            action = false;
        }
    }
   
    @Override
    public void run() {
        while(working){
            working();
        }
    }

}

当用户线程结束后,守护线程自动就会结束。
守护线程需要注意的是:
一、凡事在守护线程中创建的线程,默认都是守护线程;
二、当线程起来后,就不能再将该线程设置为守护线程,则会导致IllegalThreadStateException;
三、守护线程不要负责主要的业务,因为守护线程的结束并不是由所要执行的业务代码所决定。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值