学习java22天

/*

  • 主线程 执行main()方法的线程
  • 单线程程序:只有一个线程在执行,从头到尾 */
public class Demo01MAainThread {
    public static void main(String[] args) {
        Person p1=new Person("小强");
        p1.run();

//        System.out.println(0/0);

        Person p2=new Person("小刚");
        p2.run();
    }
}
  • 实现步骤:
  • 1.创建一个Thread类的子类
  • 2.在Thread子类中重写run方法,设置线程任务(干什么)
  • 3.创建Thread子类的对象
  • 4.调用Thread类中的方法start来启动线程,执行run方法
public class Demo01Thread {
	public static void main(String[] args) {
		//3.创建Thread子类的对象
		MyThread mt=new MyThread();
		//4.调用start方法
		mt.start();
		for(int i=0; i<20;i++) {
			System.out.println("主线程:"+i);
			//if(i==10)
			//	System.out.println(0/0);
	}
	}
}
  • 实现runnable接口创建多线程的好处:
    1.避免了单继承的局限性
    2.增强了程序的扩展性,降低了程序的耦合性
package demo04;
public class Demo04Runnable {
public static void main(String [] args) {
	//3.创建一个runnable接口的实现类 对象
	RunnableImpl run=new RunnableImpl();
	//4.创建Thread类对象,构造方法中传递Runnable接口实现类对象
	//Thread t=new Thread(run);
	//5.调用Thread类重点start方法,启动子线程
	Thread t=new Thread(new RunnableImpl2());
	t.start();
	for(int i=0;i<20;i++) {
		System.out.println(Thread.currentThread().getName()+"-->"+i);
	}
}
}

注意:
1.通过代码块中的锁对象,可以使用任意的对象
2.但是必须保证多个线程使用的锁对象是同一个
3.锁对象作用:
把同步代码块锁住:只让一个线程执行

 public class RunnableImpl  implements Runnable {
	private int ticket=100;
	Object obj=new Object();
	@Override
	public void run() {
		while(true) {
			synchronized(obj) {
			if(ticket>0) {
				try {
				Thread.sleep(10);
				}catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+"-->正在卖第"+ticket+"张票");
				ticket--;
			}
			}
		}
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值