JAVA多线程 <一>两种开启方式

JAVA多线程的两种开启模式:

package thread_Demo; 
/*
 * 本段程序演示多线程的第一种使用方式:直接继承Thread类
 * */
class ContinueThead extends Thread {
	private String name;
	ContinueThead(String name){
		this.name = name ;
	}
	//重写run方法
		public  void  run(){
			for (int count = 0; count != 10; ++count){
				System.out.println(name+"..................."+count);
			}
		}
}
public class ThreadDemo {
	public static void main(String[] args) {
		ContinueThead t1 = new ContinueThead("线程1");
		ContinueThead t2 = new ContinueThead("线程2");
		t1.start();
		t2.start();
	}

}



package thread_Demo;
/*
 * 本段程序演示多线程的第二种使用方式:实现implements接口
 * */
class ContinueThread implements  Runnable 
{
	private int num = 10;
	public void run()
	{
	   for (int count = 0; count != 10;++count){	
		   if (num>0)
			   System.out.println(Thread.currentThread().getName()+".....t......"+num--);
		}
	}
}
public class ThreadDemo2
{
	public static void main(String[] args) {
		ContinueThread t = new ContinueThread();
		new Thread(t).start();
		new Thread(t).start();
	}

}


但是第二种执行模式会存在安全问题(来源于CPU的随机切换性):


解决方法:用到关键字synchronized



package thread_Demo;
/*
 * 本段程序演示多线程的第二种使用方式:实现implements接口
 * */
class ContinueThread implements  Runnable 
{
	private int num = 10;
        Object obj = new Object();
	public void run()
	{
		
			   for (int count = 0; count != 10;++count){	
				<span style="font-family: Arial, Helvetica, sans-serif;">synchronized (obj) {   //这里相当一个锁,保证一次只有一个线程在执行,其他线程进不来</span><span style="font-family: Arial, Helvetica, sans-serif;">   </span>
					   if (num>0){
						   try{
							   		Thread.sleep(10);            //休眠10ms
							   }catch (InterruptedException e )
							   { }
						   System.out.println(Thread.currentThread().getName()+".....t......"+num--);
					   }
					}
	   }
	}
}
public class ThreadDemo2
{
	public static void main(String[] args) {
		ContinueThread t = new ContinueThread();
		new Thread(t).start();
		new Thread(t).start();
	}

}

但是使用了同步以后,可能还是会出现安全问题,这是可能就是同步代码块写的有问题了。

同步的前提:

多个线程在同步中,必须使用同一个锁,这才是对多个线程同步(1.是多线程并且共享资源;2.是使用同一个synchronized)

注意1. synchronized(obj)和synchronized(new Object())的区别,前者是同一个锁,后者是一个线程一个锁

         2.需要同步的我们才同步,不需要同步的不要同步

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值