public class MyThread extends Thread {
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(getName() + i + "线程开始了");
}
}
}
然后创建一个main方法,来测试线程
public class Demo01 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("可乐");
MyThread mt2 = new MyThread("猫儿");
mt1.start();
mt2.start();
// mt1.run();
// mt2.run();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + i + "线程开始了");
}
}
}
然后创建一个main方法,来测试线程
public class Demo01 {
public static void main(String[] args) {
//创建MyRunnable 的对象
MyRunnable mr = new MyRunnable();
创建Thread类的对象,把MyRunnable对象作为构造方法的参数
Thread t1 = new Thread(mr,"可乐");
Thread t2 = new Thread(mr,"猫儿");
//启动线程
t1.start();
t2.start();
}
}
public class MyCallable implements Callable {
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "跟女孩表白"+ i );
}
//返回值就表示线程运行完毕之后的结果
return "答应";
}
}
然后编写一个main方法,进行测试
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//线程开启之后需要执行里面的call方法
MyCallable mt = new MyCallable();
//可以获取线程执行完毕之后的结果.也可以作为参数传递给Thread对象
FutureTask<String> ft = new FutureTask(mt);
//创建线程对象
Thread t1 = new Thread(ft,"可乐");
//启动线程
t1.start();
System.out.println(ft.get());
}
}