java 多线程的一些东西
1.两种方式实现多线程
????????????? ?一种是继承Thread类,一种是实现Runnable接口;
?????????????? Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限
????????????????
public class XunleiInterviewMultithread {public static void main(String[] args) {XunleiLock lock = new XunleiLock();new Thread(new XunleiPrinter("A", lock)).start();new Thread(new XunleiPrinter("B", lock)).start();new Thread(new XunleiPrinter("C", lock)).start();}}class XunleiPrinter implements Runnable {private String name = "";private XunleiLock lock = null;private int count = 10;public XunleiPrinter(String name, XunleiLock lock) {this.name = name;this.lock = lock;}@Overridepublic void run() {while (count > 0) {synchronized (lock) {if (lock.getName().equalsIgnoreCase(this.name)) {System.out.print(name);count--;if (this.name.equals("A")) {lock.setName("B");} else if (this.name.equals("B")) {lock.setName("C");} else if (this.name.equals("C")) {lock.setName("A");}}}}}}class XunleiLock {public String name = "A";public String getName() {return name;}public void setName(String name) {this.name = name;}}
?
?
方法(二)线程类修改如下,其他类一样:
class XunleiPrinter2 implements Runnable {
?????? private String name = "";
?????? private XunleiLock lock = null;
?????? private int count=10;
?????? public XunleiPrinter2(String name, XunleiLock lock) {
????????????? this.name = name;
????????????? this.lock = lock;
?????? }
?????? @Override
?????? public void run() {
????????????? while(count>0) {
???????????????????? synchronized (lock) {
??????????????????????????? while(!lock.getName().equalsIgnoreCase(this.name)) {
?????????????????????????????????? try{
????????????????????????????????????????? lock.wait();
?????????????????????????????????? }catch(InterruptedException e){
????????????????????????????????????????? e.printStackTrace();
?????????????????????????????????? }
??????????????????????????? }
??????????????????????????? System.out.print(name);
??????????????????????????? count--;
??????????????????????????? if (this.name.equals("A")) {
?????????????????????????????????? lock.setName("B");
??????????????????????????? } elseif (this.name.equals("B")) {
?????????????????????????????????? lock.setName("C");
??????????????????????????? } elseif (this.name.equals("C")) {
?????????????????????????????????? lock.setName("A");
??????????????????????????? }
??????????????????????????? lock.notifyAll();
???????????????????? }
????????????? }
?????? }
}
来源:http://www.blogjava.net/hankchen