天天看点

Java线程

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/53487378

Callable 可以返回值

ExecutorServers

ExecutorServers ser = ExevuteServers.newFixedThread()

Future result = sesr.submit(类);

ser.shutdownNow();

停止线程

线程类中定义线程体使用的标志

线程提内使用该标志

提供对外的方法改变该标识

外部调用方法改变标识

run (){

while(flag){

}

}

阻塞

join()合并线程

yeild()暂停当前正在执行的线程,执行其他线程static

sleep()暂停,不释放锁

–> 与时间相关

–> 模拟网络延时

system.currentTimeMillis()当前时间

//join 合并线程,执行当前线程时加入另一个线程,并等待另一个线程执行完毕

import java.util.Locale.Category;

public class Test1 {
    public static void main(String [] args) throws InterruptedException{
        home m = new home();

        Thread cat = new Thread(m); 
        cat.setName("cat");
        cat.start();

        for(int i = 0 ; i< 10; i++){
            cat.join();
            System.out.println("main");
        }
    }
}
class home implements Runnable{
    public void run() {
        for (int i = 0 ; i < 10 ; i++){
            System.out.println("This is "+Thread.currentThread().getName()+i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}
           
// yield 暂停本线程执行其他线程(虽然在我电脑上试没有任何反应。。。)
        for(int i = 0 ; i< 10; i++){
//          if(i%2==0)
            Thread.yield();
            System.out.println("main");
        }
           

优先级

*MAX_PRIOIRTY 10

NORM_PRIOIRTY 5

MIN_PRIOIRTY 1*

isAlive() 判断线程是否还活着

Thread.currentThread()当前线程 static

getName()

*setPriority()

优先级代表概率,不是绝对的先后顺序*

线程的同步与锁定

多个线程访问同一资源:线程安全

StringBuffer–append

hashtable

1.同步块/同步方法

同步方法:

package 线程;

import java.util.*;

import One.sss;

public class tongbu {
    public static void main(String [] args) throws InterruptedException{
        a m = new a();

        Thread cat = new Thread(m);
        Thread dog = new Thread(m);

        cat.setName("cat");
        dog.setName("dog");

        cat.start();
        dog.start();

    }
}

class a implements Runnable{
    int s =10;
    @Override
    public  void run() {
        // TODO Auto-generated method stub
            test1();
    }

    private synchronized void test1(){
        for (int i = 0 ; i < 10 ; i++){
            if (s<=0)
                break;
            System.out.println(Thread.currentThread().getName()+"get"+s--);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
           

同步块:

synchronize(引用类型)

{ 同步的部分 }

//同步块,参数为引用`
private  void test2(){
    synchronized(this){
        for (int i = 0 ; i < 10 ; i++){
            if (s<=0)
                break;
            System.out.println(Thread.currentThread().getName()+"get"+s--);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
           

锁定范围难把握

线程安全的效率相对低下

单例设计模式

一个类只有一个对象

双重检查

1、懒汉式:

将构造器设为私有。避免外部直接创建对象

声明私有的静态属性

对外部提供访问属性的静态方法,确保对象的存在

锁定静态的信息(XXX.class)

2、饿汉式

声明私有的静态属性,同时创建对象

对外部提供访问属性的静态方法

RunTime

//懒汉式
//可以满足要求但是效率不高
package 线程;

public class 单例 {
    public static void main(String[] args) throws InterruptedException {
        test s1 = new test();
        test s2 = new test();

        s1.start();
        s2.start();
    }
}

class Single {

    private static Single data = null;
    // 私有的构造函数
    private Single(){
    }

    //提供外界访问的函数
    public static synchronized Single getInstance() throws InterruptedException{
        if(null == data){
            Thread.sleep(1000);
            data = new Single();
        }
        return data;
    }
}

class test extends Thread{
    public void run(){
        try {
            System.out.println(Single.getInstance());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//      System.out.println(b);
    }
}
           
//可以使用块同步
    public static Single getInstance2() throws InterruptedException{
        synchronized(Single.class){
            if(null == data){
                Thread.sleep(1000);
                data = new Single();
            }
            return data;
        }
    }
           
//双重检查
    public static Single getInstance3() throws InterruptedException {
        if (null == data) {
            synchronized (Single.class) {
                if (null == data) {
                    Thread.sleep(1000);
                    data = new Single();
                }
            }
        }
        return data;
    }
           

饿汉式

private static Single data = new Single();

声明时创建

过多的同步方法可能造成死锁

生产者消费者模式

wait()等待,释放锁

notify() 通知正在等待的线程-和同步一起使用

notifyAll() 通知多个线程

package 生产者消费者模式;

import javax.security.auth.login.FailedLoginException;

public class Moive {
    private String moive;
    boolean flag = true;

    public synchronized void play(String m){
        if (!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (flag){
            try {
                this.moive = m;
                Thread.sleep(500);
                System.out.println("已经放映电影:"+moive);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = false;
            notify();
        }
    }

    public synchronized void watch() {
        if (flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (!flag) {

            try {
                Thread.sleep(200);
                System.out.println("正在观看电影:" + moive);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            flag = true;
            notify();
        }
    }
}
           

Timer定时器

*一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

*

schedule(TimerTask task, Date firstTime, long period)

安排指定的任务在指定的时间开始进行重复的固定延迟执行。

schedule(TimerTask task, Date time)

安排在指定的时间执行指定的任务。

schedule(TimerTask task, long delay)

安排在指定延迟后执行指定的任务。

::TimerTask(使用Runnable接口的方法)