线程

来源:互联网 发布:河北新闻联播网络直播 编辑:程序博客网 时间:2024/06/05 23:41

1 java

1.1.1

class MThread extends Thread {  
    @Override
    public void run() {
        super.run();
    }
}
MThread mt = new MThread();
mt.start();

1.1.2

class MRun implements Runnable {
    int m = 100;
    public void run() {
        while (m > 0) {
            System.out.println(m-- + "   " + Thread.currentThread().getName());
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

MRun run = new MRun();

Thread t = new Thread(run, "a");
Thread t1 = new Thread(run, "b");
t.start();
t1.start();

1.1.1与1.1.2最大的区别就是1.1.2中可以实现数据共享  需要注意的就是所有Thread初始化完再start  如果new一个直接start  则不会共享

1.2 Runnable与Callable<V>

都是实现任务的接口 区别:

callable有返回值  runnable没有

callable runnable都可以用于Executors  但是Thread只能用runnable

1.3 线程池

总结的蛮好的文章 http://www.cnblogs.com/dolphin0520/p/3932921.html

Executors.newCachedThreadPool();// 线程池里有很多线程需要同时执行,老的可用线程将被新的任务触发重新执行,如果线程超过60秒内没执行,那么将被终止并从池中删除

Executors.newFixedThreadPool(5);//拥有固定线程数的线程池,如果没有任务执行,那么线程会一直等待

Executors.newSingleThreadExecutor();//只有一个线程的线程池,因此所有提交的任务是顺序执行

Executors.newScheduledThreadPool(5);//用来调度即将执行的任务的线程池

1.4 同步

1.4.1 synchronized

最常用的方法了   主要有锁对象 锁方法

1.4.2 volatile

每次都获得最新的值 且不是原子性的

1.4.3 ReentrantLock

ReentrantLock类是可重入、互斥、实现了Lock接口的锁, 

它与使用synchronized方法具有相同的基本行为和语义,并且扩展了其能力
1.4.4 AtomicInteger
原子操作
1.4.5 ThreadLocal
每个线程都有独立的一个副本  不太明白跟同步有什么关系

2 python
2.1
import threading
import time
mylock = threading.RLock()              #同步锁  mylock.acquire()获得锁    mylock.release()释放锁
class MThread(threading.Thread):        #继承Thread
    def __init__(self, name, interval):
        threading.Thread.__init__(self)
        self.name = name
        self.interval = interval
        self.stopFlag = False
    def run(self):
        while not self.stopFlag:
            mylock.acquire()
            print 'Thread  name:%s  time:%s' % (self.name, time.ctime())
            time.sleep(self.interval)
            mylock.release()
    def stop(self):
        self.stopFlag = True
t1 = MThread("t1", 1)
t2 = MThread("t2", 2)
t1.start()
t2.start()
t2.join()           #一直等 直到t1结束
#time.sleep(10)
t1.stop()
t2.stop()
还有一种将函数传入Thread的方式
2.2 同步
2.2.1 RLock  临界区
2.2.2 Condition 扩展RLock 实现复杂的控制
con=threading.Condition()
con.acquire()
con.wait()
con.notify()
con.release()
2.2.3 semaphore 
2.2.4 event


0 0