当前位置: 技术问答>java相关
java 多线程问题.
来源: 互联网 发布时间:2015-10-28
本文导语: 如果要实现2个线程,除了主线程外,另外增加一个线程.在Applet中.典型的方法是: public class aa extends Applet implements Runnable { Thread thread1; public void start() { if(thread1==null) { thread1=new Thread(this); thread1.start(...
如果要实现2个线程,除了主线程外,另外增加一个线程.在Applet中.典型的方法是:
public class aa extends Applet implements Runnable
{
Thread thread1;
public void start()
{
if(thread1==null)
{
thread1=new Thread(this);
thread1.start();//调用run()
}
}
public void stop()
{
if(thread1!=null)
{
thread1.stop();
thread1=null;
}
}
public void paint(Graphics g)
{
......
}
public void run()
{
while(true)
{
......
repaint();
}
}
}
现在问题是:如果要实现更多的线程,如Thread2...该怎么改呢?
public class aa extends Applet implements Runnable
{
Thread thread1;
public void start()
{
if(thread1==null)
{
thread1=new Thread(this);
thread1.start();//调用run()
}
}
public void stop()
{
if(thread1!=null)
{
thread1.stop();
thread1=null;
}
}
public void paint(Graphics g)
{
......
}
public void run()
{
while(true)
{
......
repaint();
}
}
}
现在问题是:如果要实现更多的线程,如Thread2...该怎么改呢?
|
public class aa extends Applet {
public void init(){
Thread1 thread1=new Thread1();
thread1.start();
Thread2 thread2=new Thread2();
thread2.start();
......
}
class Thread1 extends Thread{
public void run() {}
}
class Thread2 extends Thread{
public void run() {}
}
}
public void init(){
Thread1 thread1=new Thread1();
thread1.start();
Thread2 thread2=new Thread2();
thread2.start();
......
}
class Thread1 extends Thread{
public void run() {}
}
class Thread2 extends Thread{
public void run() {}
}
}
|
public class ThreadExample extends Applet {
public ThreadExample() {
thread.start();
System.out.println("Thread Created");
}
public static void main(String[] args) {
for(int i=0;i
public ThreadExample() {
thread.start();
System.out.println("Thread Created");
}
public static void main(String[] args) {
for(int i=0;i