Java语言程序设计-进阶篇(七)多线程与并行程序设计【上】

1.简单的多线程例子

package test;

public class hello {
  public static void main(String args[]){
    Runnable printA = new PrintChar('a',100);
    Runnable printB = new PrintChar('b',100);
    Runnable printC = new PrintChar('c',100);
    
    Thread A = new Thread(printA);
    Thread B = new Thread(printB);
    Thread C = new Thread(printC);
    
    A.start();
    B.start();
    C.start();
    
  }
}

class PrintChar implements Runnable{
  private char c;
  private int i;

  public PrintChar(char c, int i) {
    this.c = c;
    this.i = i;
  }

  @Override
  public void run() {
    for(int k=0;k<i;k++)
       System.out.print(c);
    
  }
  
}

其中若将A.start()等改成A.run();最后实现的结果是打印100个A然后打印100个B最后打印100C,没有实现多线程并行操作。

2.创建一个线程池

创建一个有三个固定线程的线程池
ExecutorService exe = Executors.newFixedThreadPool(3);
创建一个可变的线程池:
ExecutorService exe = Executors.newCachedThreadPool();

3.线程同步与同步语句

package test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Account {
	private static account acc = new account();
	
	public static void main(String args[]){
		ExecutorService exe = Executors.newCachedThreadPool();
		for(int i=0;i<10000;i++){
		exe.execute(new addmoney());}
		exe.shutdown();
		while(!exe.isTerminated()){}
		System.out.println(acc.getbal());
		}

	private static class addmoney implements Runnable{
		public void run(){
			synchronized(acc){
			acc.dep(1);}}
	}

	private static class account{
		private int balance = 0;
		private int getbal(){
			return balance;
		}
	
		public void  dep(int m){
			
			int newbalance =balance+ m;
			try{
				Thread.sleep(5);
			}
			catch(InterruptedException ex){}
			balance = newbalance;
		}
			
	}	
}
其中若将
synchronized(acc)

这里acc改成this将不能实现同步。

另外可以在

public void  dep(int m)

这里加入关键字synchronized实现同步,另外在方法体中使用synchronized(this){method}也可以实现同步。使用lock也可以显示的实现锁,使用Lock lock=new ReentrantLock()创建锁。

4.线程之间协作


使用该语句可以创建线程之间的唤醒条件实现线程之间的协作

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值