public class Main {
public static void main(String[] args) {
MyThread m = new MyThread("线程A");
MyThread m1 = new MyThread("线程B");
MyThread m2 = new MyThread("线程C");
new Thread(m).start();
new Thread(m1).start();
new Thread(m2).start();
}
}
class MyThread implements Runnable{
private String name;
MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int x=0;x<10;x++){
System.out.println(this.name + "-->" + x);
}
}
}
用Runnable接口与Thread类相比,解决了单继承的定义局限,这个程序的设计模式,很像代理设计,如果是代理设计模式,客户端调用的应该是run才对
而且比Thread更能描述数据共享的概念
package com.company;
public class Main {
public static void main(String[] args) {
MyThread m = new MyThread();
new Thread(m).start();
new Thread(m).start();
new Thread(m).start();
}
}
class MyThread implements Runnable{
private int ticket = 10;
@Override
public void run() {
for(int x=0;x<100;x++){
if(this.ticket>0) {
System.out.println("卖票,ticket=" + this.ticket--);
}
}
}
}
获取线程返回结果:
public class Main {
public static void main(String[] args) throws Exception {
//public FutureTask(Callable<V> callable) 是为了取得callable的返回结果
//并且FutureTask是Runnable的子类能够作为Thread的构造参数
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
FutureTask<String> task1 = new FutureTask<String>(mt1);
FutureTask<String> task2 = new FutureTask<String>(mt2);
new Thread(task1).start();
new Thread(task2).start();
//多线程执行完毕后可以取得内容,依赖FutureTask的父接口
//Future的get()方法完成
System.out.println("mt1的返回结果:"+ task1.get());
System.out.println("mt2的返回结果:"+ task2.get());
}
}
class MyThread implements Callable<String>{
private int ticket = 10;
@Override
public String call() throws Exception {
for(int x = 0;x<100;x++){
if(this.ticket>0){
System.out.println("卖票,ticket="+this.ticket--);
}
}
return "票已经卖完";
}
}
fdf