黑马程序员_线程并发库

------- android培训java培训、期待与您交流! ----------

JDK 1.5新特性 线程并发库:

    创建线程的两种传统方式

        第一个创建线程思路:
            1.继承Thread类。
            2.覆盖Thread类中的run方法。
            3.把线程要运行的代码封装到run方法中。
            4.调用strat方法,开启一个线程并调用run方法。

<span style="font-size:14px;color:#330033;"><span style="font-size:14px;">public class TraditionalThread {
    public static void main(String[] args) { 
	new Thread() { 
	    @Override
	    public void run() { 
		while (true) { 
		    try { 
			Thread.sleep(700); 
		    } catch (InterruptedException e) { 
			e.printStackTrace(); 
		    } 
		    System.out.println(this.getName()); 
		} 
	    } 
	}.start(); 
    }
}</span></span>
            第二中创建线程思路:
                1.实现Runnbale接口。
                2.覆盖Runnable接口的run方法。
                3.创建一个线程,把Runnable子类当成参数进行传递。
                4.把线程要运行的代码封装到Runnable子类的run方法中。
                5.调用线程的start方法,开启线程并调用run方法。
<span style="font-size:14px;color:#330033;"><span style="font-size:14px;">public class TraditionalThread {
    public static void main(String[] args) { 
	new Thread(new Runnable(){ 
	    @Override
	    public void run(){ 
		while (true) { 
		    try { 
		        Thread.sleep(700); 
		    } catch (InterruptedException e) { 
			e.printStackTrace(); 
		    } 
	            System.out.println(Thread.currentThread().getName()); 
		} 
	    } 
        }).start(); 
    }
}</span></span>
    定时器的应用:  
<span style="font-size:14px;color:#330033;">import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {
    private static int count = 0; 
    public static void main(String[] args) { 
	class MyTimerTask extends TimerTask{ 
	    @Override 
	    public void run() { 
		count = (count+1)%2; 
		System.out.println("bombing"); 
		new Timer().schedule(new MyTimerTask(),2000+2000*count ); 
	    } 
	} 
	new Timer().schedule(new MyTimerTask() ,2000); 
	while(true){ 
	    System.out.println(new Date().getSeconds()); 
	    try { 
		Thread.sleep(700); 
	    } catch (InterruptedException e) { 
		e.printStackTrace(); 
	    } 
	} 
    } 
}</span>
线程之间互斥:
<span style="font-size:14px;color:#330033;">public class TraditionalThreadSynchronized {
    public static void main(String[] args) { 
	new TraditionalThreadSynchronized().init();
    } 
    private void init(){ 
        final Outputer outputer = new Outputer(); 
	new Thread(){ 
	    public void run() { 
		while(true){ 
		    try { 
			Thread.sleep(500); 
		    } catch (InterruptedException e) { 
			e.printStackTrace(); 
		    } 
		    outputer.output("黑马程序员"); 
		} 
	    } 
        }.start(); 
	new Thread(){ 
	    public void run() { 
		while(true){ 
		    try { 
			Thread.sleep(500); 
		    } catch (InterruptedException e) { 
		        e.printStackTrace(); 
		    } 
		    outputer.output("黄兴"); 
		} 
	    } 
	}.start(); 
    } 
    static class Outputer{ 
	public void output(String name){ 
	    synchronized(""){ 
		for(int x=0;x<name.length();x++){ 
		    System.out.print(name.charAt(x)); 
                } 
		System.out.println(); 
	    } 
        } 
	public synchronized void output2(String name){ 
	    for(int x=0;x<name.length();x++){ 
		System.out.print(name.charAt(x)); 
	    } 
	    System.out.println(); 
	} 
	public static synchronized void output3(String name){ 
	    for(int x=0;x<name.length();x++){ 
		System.out.print(name.charAt(x)); 
	    } 
	    System.out.println(); 
	} 
    } 
}
//总结:线程之间的互斥就是在互斥的同步代码上加锁,锁可以是任意对象,但是必须保证锁的唯一。
</span>
线程之间的通讯:
public class TraditionalThreadCommunication {
    public static void main(String... args) { 
	final ThreadStartCode threadStartCode = new ThreadStartCode(); 
	new Thread(new Runnable(){ 
	    @Override 
		public void run() { 
		    for(int x=1;x<=50;x++){ 
			threadStartCode.sub(); 
		    } 
	        } 
	}).start(); 
	for(int x=1;x<=50;x++){ 
	    threadStartCode.main(); 
	} 
    } 
} 
class ThreadStartCode{
    private boolean falg = true; 
    public synchronized void sub(){ 
	while(!falg){ 
	    try { 
	        this.wait(); 
            } catch (InterruptedException e) { 
		e.printStackTrace(); 
	} 
    } 
        for(int x=1;x<=10;x++){ 
	    System.out.println(Thread.currentThread().getName()+"......sub..."+x); 
        } 
        falg = false; 
        this.notify(); 
    } 
    public synchronized void show(){ 
	while(falg){ 
	    try { 
		this.wait(); 
	    } catch (InterruptedException e) { 
		e.printStackTrace(); 
	} 
    } 
        for(int x=1;x<=10;x++){ 
	    System.out.println(Thread.currentThread().getName()+"......show..."+x); 
        } 
        falg = true; 
        this.notify(); 
    } 
}
//线程之间的通讯,就是Object任意对象的wait方法和notify方法。但是有一个前提就是要先有锁对象。
线程范围内的共享数据:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadSopeShareData {
    private static Map<Thread,Integer> map = new HashMap<Thread,Integer>(); 
    private static int data = 0; 
    public static void main(String[] args) { 
        for(int x=1;x<=2;x++){ 
	    new Thread(new Runnable(){ 
		@Override 
		public void run() { 
		    int data =new Random().nextInt(); 
		    map.put(Thread.currentThread(),data); 
		    System.out.println(Thread.currentThread().getName()+"...."+data); 
		    new A().get(); 
		    new B().get(); 
		} 
	    }).start(); 
	} 
    } 
    static class A{ 
	public void get(){ 
	    int data = map.get(Thread.currentThread()); 
	    System.out.println("A form "+Thread.currentThread().getName() +"...get data :"+data); 
	} 
    } 
    static class B{ 
        public void get(){ 
	    int data = map.get(Thread.currentThread()); 
	    System.out.println("B form "+Thread.currentThread().getName() +"...get data :"+data); 
	} 
    } 
}
//<span style="font-size:14px;">每个线程属于自己的线程数据,就是存进去的数据是存到线程中.</span><span style="font-size:14px;">当前线程去存入数据和取数据,取出来的数据是存入的数据.(不管是不是静态)</span>
线程范围内的共享数据,封装成对象。单例设计模式:
import java.util.Random;

class Person{
    private static ThreadLocal<Person> threadLocal= new ThreadLocal<Person>();
    //单例模式(懒汉式)
    private String name;
    private int age;
    private Person(){}
        //这里是获取当前线程的实例对象。
    public static Person getInstance(){
    //由于的线程对象,所以必须保证每个线程对象都有一份 
        Person Instance =threadLocal.get();
	if(Instance == null){
	    synchronized (Person.class) {
		//判断对象是否为空
		if (Instance == null) {
		    //如果为空,则实例化该对象。
		    Instance = new Person();
	       	    //把对象设置进当前线程
		    threadLocal.set(Instance);
		}
	    }
        }
        //返回当前线程对象
        return Instance; 
    }
    public String getName() {
	return name;
    }
    public void setName(String name) {
	this.name = name;
    }
    public int getAge() {
	return age;
    }
    public void setAge(int age) {
	this.age = age;
    }
}
public class PersonThreadLocalTest {
    private static int date;
    public static void main(String[] args) {
	new PersonThreadLocalTest().intn();
    }
    public void intn(){
	for (int x = 1; x <= 5; x++) {
	    new Thread(new Runnable() {
		@Override
		public void run() {
		    int date = new Random().nextInt(11) + 13;
		    //获取当前线程的对象。 
		    Person p = Person.getInstance();
		    //给当前线程对象的age进行设置。
		    p.setAge(date);
		    //给当前线程对象的name进行设置。 
		    p.setName("黑马程序员——黄兴");
		    new A().getDate();
		    new B().getDate();
		}
	    //启动线程 
	    }).start();
	}
    }
    class A {
	public void getDate(){
            Person p = Person.getInstance();
	    System.out.println("A" + Thread.currentThread().getName() + "姓名:" + p.getName() + "年龄" + p.getAge());
	}
    }
    class B {
	public void getDate(){
	    Person p = Person.getInstance();
	    System.out.println("B" + Thread.currentThread().getName() + "姓名:" + p.getName() + "年龄" + p.getAge());
	}
    }
}
数据类型多线程并发操作:
import java.util.concurrent.atomic.AtomicInteger;

public class atomicIntegerTest {
    public static void main(String... args) { 
	AtomicInteger atomicInteger =new AtomicInteger(); 
	atomicInteger.set(20); 
	atomicInteger.addAndGet(20); 
	System.out.println(atomicInteger); 
   } 
}
线程池:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTest {
    public static void main(String[] args) { 
	ExecutorService executorService = Executors.newSingleThreadExecutor();//单一线程池 
	//Executors.newCachedThreadPool();//缓存线程池 
	//Executors.newFixedThreadPool(3);//固定大小线程池 
	for(int x=1;x<=10;x++){ 
	    final int task = x; 
	    executorService.execute(new Runnable(){ 
		@Override 
		public void run() { 
	            for(int y=1;y<=10;y++){ 
			System.out.println(Thread.currentThread().getName() +" is looping of "  + y +" for task of "+task ); 
		    } 
		} 
	    }); 
	} 
	System.out.println("over"); 
	//executorService.shutdown();//顺序关闭 
	//executorService.shutdownNow();//空闲时关闭线程池 
	//相当于TraditionThread的炸弹一样。 
	Executors.newScheduledThreadPool(3).schedule(new Runnable(){ 
	    public void run(){ 
		System.out.println("bombing"); 
	    } 
	},  
	5,  
	TimeUnit.SECONDS); 
	//连环爆炸。 
	Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){ 
	    public void run(){ 
		System.out.println("bombing"); 
	    } 
	},  
	5,  
        2, 
	TimeUnit.SECONDS); 
    } 
}
------- android培训java培训、期待与您交流! ----------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值