多线程中使用Runnable的接口与Thread类来实现,注意是Thread类不是其子类,关键是将Runnable接口作为参数进行传递
另外两个共同的类作为线程则成员变量是共享的。。。。指的是run以外的
Thread.currentThread()返回线程编号
Thread.currentThread().getName()返回设定的名字
第一个类
public class process {
public static void main(String args[]){ user use = new user(); Thread r1; Thread r2; r1=new Thread(use); r2=new Thread(use); use.inner(10); r1.setName("猫"); r2.setName("狗"); r1.start(); r2.start(); }}第二个类
class user implements Runnable{
int water; public void inner(int i){ water = i; } public void run(){ while(true){ String name = Thread.currentThread().getName(); if(name.equals("狗")){ water=water-1; System.out.println(name+"喝水"+water); } if(name.equals("猫")){ water = water-1; System.out.println(name+"喝水"+water); } try{ Thread.sleep(2000); } catch(InterruptedException e){ System.out.println("出错"); } } }}