java 多线程库_多线程的实现

[java]代码库//文件名:ThreadDemo.java

class MyThread extends Thread {//第一种方法:继承Thread类,覆写run()方法,被实例化后使用start()方法启动线程

private String name ;//线程名称

public MyThread(String name) {

this.name = name ;

}

public void run() {//覆写Thread类的run()方法;

for(int i = 0; i<10; i++) {

System.out.println(name + "运行 i = " + i) ;

}

}

}

class MyRunnable implements Runnable {

private String name ;

public MyRunnable(String name) {

this.name = name ;

}

public void run() {

for(int i = 0; i<10; i++) {

System.out.println(name + "运行 i = " + i) ;

}

}

}

public class ThreadDemo {

public static void main(String arg[]) {

new MyThread("线程A").start();//第一种继承Thread类方法,调用其start()方法启动线程

new MyThread("线程B").start();

new Thread(new MyRunnable("线程C")).start() ; //使用实例化Thread类,传入Runnable子类实例化对象,调用start()方法启动线程

MyRunnable myRun = new MyRunnable("共享资源进程") ;//实现资源共享的多线程操作

new Thread(myRun) ;//资源共享的第一个线程

new Thread(myRun) ;//资源共享的第二个线程。此方法实现多个线程公用同一对象中的数据

}

}

694748ed64b9390909c0d88230893790.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值