多线程2(2)

2019-03-23 15:08

}

}

{ }

if(ticket>0)

System.out.println(\卖票:\

public class Test { }

public static void main(String args[]) { }

MyThread th1=new MyThread(); Thread t1=new Thread(th1); Thread t2=new Thread(th1); Thread t3=new Thread(th1); t1.start(); t2.start(); t3.start();

程序运行结果如下: 卖票:5

卖票:2 卖票:1 卖票:3 卖票:4

我们可以看到3个线程共享这5张票。因为只创建了一个MyThread对象。因此采用接口可以实现资源共享。

线程的方法:

Thread.sleep():休眠

Thread.currentThread():获取当前线程

Thread.getName():获取线程的名字

Thread.currentThread().getName():获取当前线程的名字

构造方法

Thread(Runnable target,String name)

获取当前线程名字举例:

class MyThread implements Runnable {

public void run() {

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

System.out.println(Thread.currentThread().getName()+\运行\次\ } } }

public class Test {

public static void main(String args[]) {

MyThread th1=new MyThread(); Thread t1=new Thread(th1,\线程A\ Thread t2=new Thread(th1,\线程B\ Thread t3=new Thread(th1,\线程C\ t1.start(); t2.start(); t3.start(); } }

运行结果如下: 线程A运行1次

线程C运行1次 线程C运行2次 线程C运行3次 线程C运行4次 线程C运行5次 线程C运行6次 线程C运行7次 线程C运行8次 线程C运行9次 线程B运行1次 线程B运行2次 线程B运行3次 线程B运行4次 线程B运行5次 线程B运行6次


多线程2(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:南工大概率统计A卷B卷

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: