展开全部
实现多线程可以从 Thread类继承 ,实现Runnable接口,一般采32313133353236313431303231363533e59b9ee7ad9431333363373732用实现Runnable接口的方式。
以下代码仅供参考。package com.kidd.test.zhidao;
/**
* Hello world!
*
*/
public class Execute {
public static void main(String[] args) throws InterruptedException {
MyData myData = new MyData();
TestThread1 tt1 = new TestThread1(myData);
TestThread2 tt2 = new TestThread2(myData);
TestThread3 tt3 = new TestThread3(myData);
TestThread4 tt4 = new TestThread4(myData);
Thread myThread1 = new Thread(tt1);
Thread myThread2 = new Thread(tt2);
Thread myThread3 = new Thread(tt3);
Thread myThread4 = new Thread(tt4);
myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
}
}
class ThreadControl {
boolean end = false;
public boolean isEnd() {
return end;
}
}
class TestThread1 implements Runnable {
/**
* 控制线程退出
*/
boolean end = false;
private MyData myData;
public TestThread1(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
while (!end) {
synchronized (myData) {
myData.result *= 10;
System.out.println("index:" + myData.index + " TestThread1*10=" + myData.result);
myData.index++;
/**
* 唤醒等待中的线程
*/
myData.notifyAll();
try {
myData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myData.index >= 200) {
end = true;
}
}
}
}
}
class TestThread2 implements Runnable {
/**
* 控制线程退出
*/
boolean end;
private MyData myData;
public TestThread2(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
while (!end) {
synchronized (myData) {
myData.result *= 20;
System.out.println("index:" + myData.index + " TestThread2*20=" + myData.result);
myData.index++;
/**
* 唤醒等待中的线程
*/
myData.notifyAll();
try {
myData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myData.index >= 200) {
end = true;
}
}
}
}
}
class TestThread3 implements Runnable {
/**
* 控制线程退出
*/
boolean end;
private MyData myData;
public TestThread3(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
while (!end) {
synchronized (myData) {
myData.result += 30;
System.out.println("index:" + myData.index + " TestThread3+30=" + myData.result);
myData.index++;
/**
* 唤醒等待中的线程
*/
myData.notifyAll();
try {
myData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myData.index >= 200) {
end = true;
}
}
}
}
}
class TestThread4 implements Runnable {
/**
* 控制线程退出
*/
boolean end;
private MyData myData;
public TestThread4(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
while (!end) {
synchronized (myData) {
myData.result += 40;
System.out.println("index:" + myData.index + " TestThread4+40=" + myData.result);
myData.index++;
/**
* 唤醒等待中的线程
*/
myData.notifyAll();
try {
myData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myData.index >= 200) {
end = true;
}
}
}
}
}
class MyData {
int index = 0;
double result = 10;
}