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