实现Runnable

实现Runnable

  • 定义MyRunnable类实现Runnable接口
  • 实现run()方法,编写线程执行体
  • 创建对象,调用start()方法启动线程
package com.Jinone.www;

import java.io.IOException;

public class TextThread implements Runnable {

	@Override
	public void run() {
		for(int i=0;i<20;i++) {
			System.out.println("我在看代码~"+i);
		}
		
	}
	public static void main(String[] args) {
		TextThread textThread=new TextThread();
		Thread thread=new Thread(textThread);
		for(int i=0;i<20;i++) {
			System.out.println("我在学java多线程~"+i);
		}
		thread.start();
	}
	
}
	

小结

  • 继承Thread类
    1. 子类继承Thread类具备多线程能力
    2. 启动线程:子类对象.start()
    3. 不建议使用:避免oop单继承限性
  • 实现Runnable接口
    1. 实现接口Runnable具有多线程能力
    2. 启动线程:传入目标对象+Thread对象.start()
    3. 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
package com.Jinone.www;

import java.io.IOException;

public class TextThread implements Runnable {
	private int as=1;
	private static int asone,astwo,asthree;
	@Override
	public void run() {
		while(true) {
			if(as>=100) {
				System.out.println("小明一共抢到了"+asone+"张火车票");
				System.out.println("小王一共抢到了"+astwo+"张火车票");
				System.out.println("小米一共抢到了"+asthree+"张火车票");
				break;
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"抢到了第"+as+++"张火车票!");
			if(Thread.currentThread().getName().equals("小明")) {
				asone++;
			}
			if(Thread.currentThread().getName().equals("小王")) {
				astwo++;
			}
			if(Thread.currentThread().getName().equals("小米")) {
				asthree++;
			}
		}
				
		}
		
	
	public static void main(String[] args) {
		TextThread textThread=new TextThread();
		new Thread(textThread,"小明").start();
		new Thread(textThread,"小王").start();
		new Thread(textThread,"小米").start();
	}
	
}
	

结果:存在资源共享问题!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值