(1)当访问共同的代码的时候:可以使用同一个Runnable对象,这个Runnable对象中有这个共享数据,比如卖票系统就可以这么做。或者这个共享数据封装在一个对象当中,然后对这个对象加锁,也可以实现数据安全访问。
public class Interfacaesharethread {
? ? public static void main(String[] args) {
? ? ? ? Mythread1 mythread = new Mythread1();
? ? ? ? new Thread(mythread).start();
? ? ? ? new Thread(mythread).start();
? ? ? ? new Thread(mythread).start();
? ? ? ? new Thread(mythread).start();
? ? }
}
?
/* 实现Runnable接口 */
class Mythread1 implements Runnable {
? ? int index = 0;
?
? ? public synchronized void run() {
? ? ? ? while (true)
? ? ? ? ? ? System.out.println(Thread.currentThread().getName() + "is running and the index is " + index++);
? ? }
}
?(2)当各个线程访问的代码不同时:这时候要使用不同的Runnable对象,
将Runnable对象作为某一个类中的内部类,共享数据作为这个外部类的成员变量,每个线程对共享数据的访问也交给外部类的方法,比便对共享数据的互斥和通信。Runnable对象调用外部类的操作这个共享数据的方法。
public class Innersharethread {?
? ? public static void main(String[] args) {?
? ? ? ? Mythread mythread = new Mythread();?
? ? ? ? mythread.getThread().start();?
? ? ? ? mythread.getThread().start();?
? ? ? ? mythread.getThread().start();?
? ? ? ? mythread.getThread().start();?
? ? }?
}
?
/**
?* 通过内部类实现线程的共享变量
?*
?*/
class Mythread {?
? ? int index = 0;?
? ?
? ? private class InnerThread extends Thread {?
? ? ? ? public synchronized void run() {?
? ? ? ? ? ? while (true) {?
? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getName()?
? ? ? ? ? ? ? ? ? ? ? ? + "is running and index is " + index++);?
? ? ? ? ? ? }?
? ? ? ? }?
? ? }?
? ?
? ? public Thread getThread() {?
? ? ? ? return new InnerThread();?
? ? }?
}