}
}
{ }
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次