范例: 定义一个线程 1package cn.cccc.demo;2class MeThread extends Thread{3 private String title;4 public MeThread(String title){5 this.title = title;6 }7 public void run(){8 for(int x = 0; x < 10; x++){9 System.out.println(this.title + "运行 x = "+ x);10 }11 }12}13public class MyThread {14 public static void main(String[] args) {15 // TODO Auto-generated method stub6 collapsed lines16 new MeThread("线程A").start();17 new MeThread("线程B").start();18 new MeThread("线程C").start();19 20 }21} 利用卖票资源实现多个线程资源的并发访问 1package cn.cccc.demo;2class MyThread implements Runnable{3 private int ticket = 5;4 5 @Override6 public void run (){ // 线程的主体类7 for(int x = 0; x < 100; x++) {8 if(this.ticket > 0 ) {9 System.out.println("卖票、ticket = " + this.ticket--);10 }11 }12 }13}14public class ThreadDemo {15 public static void main(String[] args) {7 collapsed lines16 // TODO Auto-generated method stub17 MyThread mt = new MyThread();18 new Thread(mt).start();19 new Thread(mt).start();20 new Thread(mt).start();21 }22} 三个线程访问一个资源,总共卖五张票 callable实现多线程 从最传统的开发来讲入股偶要进行多线程的实现肯定依靠的就是Runnable,但是Runnable接口有一个缺陷就是执行后无法获取一个返回值。 Runnable的run()方法是没有返回值的。所以从jdk1.5之后就提出了一个新的线程实现 接口:java.util.concurrent.Callable接口。 1package cn.cccc.demo;2import java.util.concurrent.Callable;3import java.util.concurrent.ExecutionException;4import java.util.concurrent.FutureTask;5class MyThread implements Callable{6 public String call() throws Exception{7 for(int x = 0 ; x < 10; x++){8 System.out.println("********线程执行x+" + x);9 }10 return "线程执行完毕";11 }12}13public class ThreadDemo {14 public static void main(String[] args) throws InterruptedException, ExecutionException {15 // TODO Auto-generated method stub8 collapsed lines16 17 FutureTask<String> task = new FutureTask<>(new MyThread());18 new Thread(task).start();19 System.out.println("【线程返回数据】"+ task.get());20 21 22 }23}