流世幻羽

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1.Thread常用API

public Thread() :分配一个新的线程对象。
public Thread(String name) :分配一个指定名字的新的线程对象。
public Thread(Runnable target) :分配一个带有指定目标新的线程对象。
public Thread(Runnable target,String name) :分配一个带有指定目标新的线程对象并指定名字。
常用方法:
public String getName() :获取当前线程名称。
public void start() :导致此线程开始执行; Java虚拟机调用此线程的run方法。
public void run() :此线程要执行的任务在此处定义代码。
public static void sleep(long millis) :使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)。
public static Thread currentThread() :返回对当前正在执行的线程对象的引用。

 

2.Runable 卖票案例,实现共享数据

实现Runnable接口比继承Thread类所具有的优势:
1. 适合多个相同的程序代码的线程去共享同一个资源。
2. 可以避免java中的单继承的局限性。
3. 增加程序的健壮性,实现解耦操作,代码可以被多个线程共享,代码和线程独立。
4. 线程池只能放入实现Runable或Callable类线程,不能直接放入继承Thread的类。
扩充:在java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用
java命令执行一个类的时候,实际上都会启动一个JVM,每一个JVM其实在就是在操作系统中启动了一个进
程。

 

package com.ithuanyu;


public class Cat implements Runnable {
    public int num = 100;

    @Override
    public void run() {
        System.out.println(123);
    }
    //匿名内部类的操作


    public static void main(String[] args) {
        //卖票
        Cat cat = new Cat() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());

                while (true) {
                    synchronized (this) {
                        if (num > 1) {
                            num--;
                            System.out.println(Thread.currentThread().getName() + "正在卖" + num);
                        }
                    }
                }
            }
        };
        Thread thread = new Thread(cat, "one");
        Thread thread2 = new Thread(cat, "two");
        Thread thread3 = new Thread(cat, "three");
        thread.start();
        thread2.start();
        thread3.start();
    }
}

 

3.Lock 

java.util.concurrent.locks.Lock 机制提供了比synchronized代码块和synchronized方法更广泛的锁定操作,
同步代码块/同步方法具有的功能Lock都有,除此之外更强大,更体现面向对象。
Lock锁也称同步锁,加锁与释放锁方法化了,如下:
public void lock() :加同步锁。
public void unlock() :释放同步锁

public class Ticket implements Runnable{
private int ticket = 100;    
   
Lock lock new ReentrantLock();    
/*    
 * 执行卖票操作    
 */    
@Override    
public void run() {    
//每个窗口卖票的操作         
//窗口 永远开启         
while(true){        
lock.lock();            
if(ticket>0){//有票 可以卖            
//出票操作                 
//使用sleep模拟一下出票时间                 
try {                
Thread.sleep(50);                    
} catch (InterruptedException e) {                
// TODO Auto‐generated catch block                    
e.printStackTrace();                    
}                
//获取当前线程对象的名字                 
String name = Thread.currentThread().getName();                
System.out.println(name+"正在卖:"+ticket‐‐);                
}            
lock.unlock();            
}        
}    
}

 

  /**
     * 多线程,并行操作
     */
    public void test01() throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        CountDownLatch latch = new CountDownLatch(8);
        for (int i = 0; i < 8; i++) {
            try {
                pool.submit(()->{
                    System.out.println(Thread.currentThread().getName());
                });
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
        latch.await();
    }
    /**
     * 多线程,并行操作
     */
    @Test
    public void test02(){
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 8; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }

  

posted on 2019-08-01 09:57  流世幻羽  阅读(165)  评论(0编辑  收藏  举报