java 多线程总结

实现线程的方式:

  • 实现Runnable接口
  • 继承Thread对象
  • 使用ExecutorService、Callable、Future实现有返回结果的多线程
public class MyThread {
	public static void main(String[] args) throws Exception {
		
		// 实现Runnable接口创建线程
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				// to do
			}
		});
		t1.start();
		
		// 继承Thread创建线程
		Thread t2 = new Thread() {
			public void run() {
				// to do
			}
		};
		t2.start();
		
		// 实现callable接口,使用线程池启动线程
		   ExecutorService pool = Executors.newFixedThreadPool(2);  
		   // 创建多个有返回值的任务  
		   List<Future<Integer>> list = new ArrayList<Future<Integer>>();  
		   for (int i = 0; i < 2; i++) {  
		    Callable<Integer> c = new Callable<Integer>() {
				public Integer call() throws Exception {
					// to do
					return 0;
				}
		    	
		    };  
		    // 执行任务并获取Future对象  
		    Future<Integer> f = pool.submit(c);  
		    list.add(f);  
		   }  
		   // 关闭线程池  
		   pool.shutdown();  
		  
		   // 获取所有并发任务的运行结果  
		   for (Future f : list) {  
		    // 从Future对象上获取任务的返回值,并输出到控制台  
		     System.out.println(f.get().toString());  
		   }  
	}
}

 

线程同步方式:

  • 在方法上添加synchronized关键字, 如果加在静态方法上默认的lock为当前类的class, 如果加在非静态方法上则默认的lock为this
  • 在代码块上添加synchronized关键字
  • 使用信号量标记java.util.concurrent.Semaphore, 创建一个信号量标记,则一次只有一个线程执行
  • 使用volatile关键字修饰要同步的变量(只能确保可见性,不能确保原子性。当只有一个写的线程时才可以使用)
  • 使用ThreadLocal创建局部变量
  • 使用java.util.concurrent.atomic包中的类创建同步变量, 如AtomicInteger
  • 使用java.util.concurrent.locks包来创建锁, 通过编程方式获取和释放锁

 

public class TestThread{
    private Object lock = new Object();
    private Semaphore semaphore = new Semaphore(1);
    /**
     * 在代码块上加锁
     */
    public void test1() {
        synchronized(lock) {
             // to do
        }
    }

    /**
     * 在非静态方法上添加synchronized,以this作为锁
     */
    synchronized public void test2() {
        // to do
    }
    
    /**
     * 在静态方法上添加synchronized,以 TestThread.class作为锁, 号称“静态锁”
     */
    synchronized public static void test3{
        // to do
    }
    /**
     * 使用信号标记来控制执行的线程数量
     */
    public void test4() {
        semaphore.acquire();// 获取信号标记的线程才会继续执行
        // to do
        semaphore.release(); // 执行完后释放信号标记
    }
    
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lic0112

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值